Compare commits

...
6 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 27673ee68f fix: location overview includes devices without a location
Devices with only a site (e.g. radio bridge APs) were dropped from the
location overview, so their cables and wireless links disappeared.
They are now grouped in a per-site node "ohne Lokation".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 13:18:48 +01:00
MrBlakeandClaude Opus 5.5 174a41e838 feat: wireless links in topology, own top-level navigation menu
Interfaces with a WirelessLink are now traced like cables; wireless-only
connections are drawn blue and dotted with a "Funk" label, also in the
location overviews (counted as "1× Funk"). The plugin gets its own
"Kunden-Export" menu with icon in the main navigation instead of the
Plugins dropdown.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 13:14:16 +01:00
MrBlakeandClaude Opus 5.5 d7c86289b1 Merge origin/main (i18n) with cross-site location overview
Resolve conflicts between the i18n refactor and the new cross-site
location overview: new strings use gettext with German translations
(.po/.mo updated), version bumped to 0.18.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 13:06:46 +01:00
MrBlakeandClaude Opus 5.5 9735164da1 feat: cross-site location overview in a single diagram
New topology scope 'Lokationsübersicht standortübergreifend' draws all
locations of all sites in scope as one graph, with site and parent
location on each node, to show how buildings and locations connect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 13:03:41 +01:00
MrBlakeandClaude Opus 5.5 38b3ec2a27 Merge branch 'feat/i18n' into main
Bring the English/German translation up to date with main. Conflicts are
resolved in favour of main's features (rack photos, floor plans, CPU & RAM,
virtualization clusters, location overview, merged disk table), with their
texts now translatable and added to the German catalogue.

Bump version to 0.17.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:17:06 +01:00
MrBlakeandClaude Opus 5.5 9dba7e07a0 feat(i18n): English source strings with German translation
All UI texts and generated document texts use gettext; exports follow the user's language. Adds a check that README and PluginConfig version ranges match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 21:27:47 +01:00
37 changed files with 2216 additions and 457 deletions

No files matched your search

+9 -5
View File
@@ -38,8 +38,8 @@ document: management/OOB IPs, VMs, topology labels, prefixes and IP addresses.
All queries respect NetBox permissions (`.restrict(user, "view")`) — a
technician only exports what they are allowed to see.
Open it via the **Customer doc** button on site, location, tenant and tenant
group pages, or via **Plugins → Customer documentation**. Output formats:
Open it via the **Customer Docs** button on site, location, tenant and tenant
group pages, or via **Customer Export → Customer Documentation** in the main navigation. Output formats:
**PDF**, **Word** and **HTML preview** (opens in a new tab).
## Compatibility
@@ -47,6 +47,8 @@ group pages, or via **Plugins → Customer documentation**. Output formats:
- NetBox `4.6.8` – `4.7.x`
- Python `>=3.10`
- System libraries for PDF and rack graphics in Word: Pango, Cairo
- Languages: English and German. The interface and the exported documents follow
the language set in the user's NetBox preferences.
## Installation
@@ -180,7 +182,7 @@ sudo systemctl restart netbox netbox-rq
### Branding in NetBox (recommended)
Under **Plugins → Branding profiles**, admins create design profiles directly in NetBox:
Under **Customer Export → Branding Profiles**, admins create design profiles directly in NetBox:
- name, company name, footer and **logo upload** (PNG/JPG)
- colours via colour picker: primary, accent, table header text, labels, zebra stripes
@@ -256,13 +258,15 @@ style of Cisco Packet Tracer:
- The top-to-bottom layout follows the cabling: provider → firewall/router → core → access → end devices, with ordering optimised for as few crossings as possible.
- Lines are routed **orthogonally** on bus bars, coloured per upstream device. Port names sit at the target device; multiple uplinks are drawn thicker and marked "2×".
- **Scope**: *entire network* (one page per site), *location overview* and/or *per rack* (one page per rack). In the rack view, directly connected devices outside the rack appear faded and dashed, with their rack.
- The **location overview** draws one diagram per site with the **locations as nodes** (server room, halls, sub-distributions …). Lines are the physical cables between locations, labelled with count and cable type (e.g. `2× SMF, 4× CAT6a`), so you can follow the cabling from the server room to the last sub-distribution. Locations containing firewalls, routers or core switches are placed at the top; each node shows its parent location and the number of racks and devices.
- The **location overview** draws one diagram per site with the **locations as nodes** (server room, halls, sub-distributions …). Lines are the physical cables between locations, labelled with count and cable type (e.g. `2× SMF, 4× CAT6a`), so you can follow the cabling from the server room to the last sub-distribution. Locations containing firewalls, routers or core switches are placed at the top; each node shows its parent location and the number of racks and devices. Devices without a location (e.g. radio bridges on the roof) are grouped in a node for their site ("without location").
- The **cross-site location overview** puts all locations of all sites in scope into **one diagram**; each node shows its site (and parent location), so you can see how buildings and their locations are connected to each other.
- Each topology gets its **own landscape page** (PDF and Word) and is scaled as large as possible.
- Provider circuits appear as a cloud, devices of other sites dashed (can be disabled).
- **Wireless links** (NetBox *Wireless links*, e.g. point-to-point radio bridges) appear as blue dotted lines labelled "Wireless", in the network view as well as in the location overviews.
- Selectable labels: management IP, model, ports on links.
- Device names longer than 15 characters are wrapped, preferably at `-`, `_`, `.` or spaces.
**Symbols** (menu **Plugins → Topology symbols**, or the "Topology symbol"
**Symbols** (menu **Customer Export → Topology Symbols**, or the "Topology symbol"
button on device type and device role pages):
1. per **device type**: choose a built-in symbol or **upload a custom icon** (PNG/JPG, ideally transparent)
+4 -3
View File
@@ -1,11 +1,12 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginConfig
class CustomerExportConfig(PluginConfig):
name = "netbox_customer_export"
verbose_name = "Kunden-Export"
description = "Kundendokumentation als PDF oder Word exportieren"
version = "0.16.0"
verbose_name = _("Customer Export")
description = _("Export customer documentation as PDF or Word")
version = "0.19.1"
author = "Claude"
base_url = "customer-export"
min_version = "4.6.8"
+4 -3
View File
@@ -3,6 +3,7 @@ import base64
from dataclasses import dataclass, field
from django.utils.text import slugify
from django.utils.translation import gettext as _
EMPTY = "—"
@@ -53,11 +54,11 @@ def REF(text, target, prefix=""):
def T(headers, rows):
return Block("table", headers=list(headers), rows=[[fmt(c) for c in r] for r in rows])
return Block("table", headers=[str(h) for h in headers], rows=[[fmt(c) for c in r] for r in rows])
def KV(pairs, skip_empty=True):
rows = [[k, fmt(v)] for k, v in pairs if not (skip_empty and v in (None, "", [], EMPTY))]
rows = [[str(k), fmt(v)] for k, v in pairs if not (skip_empty and v in (None, "", [], EMPTY))]
return Block("kv", rows=rows)
@@ -91,7 +92,7 @@ def fmt(value):
if value is None or value == "":
return EMPTY
if isinstance(value, bool):
return "Ja" if value else "Nein"
return _("Yes") if value else _("No")
if isinstance(value, (list, tuple, set)) or hasattr(value, "all"):
items = value.all() if hasattr(value, "all") else value
return ", ".join(str(i) for i in items) or EMPTY
+3 -3
View File
@@ -6,10 +6,10 @@ from netbox.plugins import get_plugin_config
PLUGIN = "netbox_customer_export"
DEFAULT_BRANDING = {
"name": "Standard",
"name": "Default",
"company_name": "",
"logo_path": None,
"footer_text": "Vertraulich – nur für den internen Gebrauch des Kunden",
"footer_text": "Confidential – for the customer's internal use only",
"primary_color": "1F4E79", # Überschriften, Tabellenköpfe
"accent_color": "2E75B6", # Unterüberschriften
"header_text_color": "FFFFFF", # Schrift im Tabellenkopf
@@ -31,7 +31,7 @@ def _normalize(profile):
for key in COLOR_KEYS:
value = str(profile[key]).lstrip("#")
if not _HEX.match(value):
raise ValueError(f"netbox_customer_export: {key}={profile[key]!r} ist keine Hex-Farbe (z.B. '1F4E79')")
raise ValueError(f"netbox_customer_export: {key}={profile[key]!r} is not a hex colour (e.g. '1F4E79')")
profile[key] = value.upper()
return profile
+15 -13
View File
@@ -4,6 +4,8 @@ from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from django.utils.formats import date_format
from django.utils.translation import gettext as _
from django.views import View
from .blocks import KV, P, T, Document, H
@@ -40,7 +42,7 @@ class BrandingEditView(PermissionRequiredMixin, View):
form = BrandingProfileForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
obj = form.save()
messages.success(request, f"Branding-Profil „{obj}“ gespeichert.")
messages.success(request, _("Branding profile “%(name)s” saved.") % {"name": obj})
return redirect(f"plugins:{APP}:branding_list")
return render(request, self.template_name, {"object": obj, "form": form})
@@ -58,7 +60,7 @@ class BrandingDeleteView(PermissionRequiredMixin, View):
if f:
f.delete(save=False)
obj.delete()
messages.success(request, f"Branding-Profil „{name}“ gelöscht.")
messages.success(request, _("Branding profile “%(name)s” deleted.") % {"name": name})
return redirect(f"plugins:{APP}:branding_list")
@@ -70,24 +72,24 @@ class BrandingPreviewView(PermissionRequiredMixin, View):
def get(self, request, pk):
obj = get_object_or_404(BrandingProfile, pk=pk)
blocks = [
H(1, "Übersicht"),
KV([("Standort", "Musterstandort"), ("Status", "Aktiv"), ("Anschrift", "Musterstraße 1\n12345 Musterstadt")]),
H(2, "Geräte"),
H(1, _("Overview")),
KV([(_("Site"), _("Sample site")), (_("Status"), _("Active")), (_("Address"), _("1 Sample Street\nSample City"))]),
H(2, _("Devices")),
T(
["Name", "Hersteller / Modell", "Rack / HE", "Management-IP"],
[_("Name"), _("Manufacturer / model"), _("Rack / U"), _("Management IP")],
[
["SW-CORE-01", "HPE Aruba 6100", "Rack A / HE 20", "10.0.0.2/24"],
["SW-ACC-01", "HPE Aruba 6000", "Rack A / HE 18", "10.0.0.3/24"],
["FW-01", "Sophos XGS 2100", "Rack A / HE 16", "10.0.0.1/24"],
["SW-CORE-01", "HPE Aruba 6100", _("Rack A / U %(u)s") % {"u": 20}, "10.0.0.2/24"],
["SW-ACC-01", "HPE Aruba 6000", _("Rack A / U %(u)s") % {"u": 18}, "10.0.0.3/24"],
["FW-01", "Sophos XGS 2100", _("Rack A / U %(u)s") % {"u": 16}, "10.0.0.1/24"],
],
),
P("So sehen Überschriften, Tabellen und Fließtext mit diesem Profil aus."),
P(_("This is how headings, tables and body text look with this profile.")),
]
doc = Document(
title="Netzwerkdokumentation Vorschau",
subtitle="Beispielkunde",
title=_("Network documentation preview"),
subtitle=_("Sample customer"),
blocks=blocks,
meta={"author": request.user.username, "date": timezone.localtime().strftime("%d.%m.%Y")},
meta={"author": request.user.username, "date": date_format(timezone.localdate(), "SHORT_DATE_FORMAT")},
branding=_normalize(obj.as_branding()),
)
return HttpResponse(render_html(doc), content_type="text/html; charset=utf-8")
+10 -8
View File
@@ -1,5 +1,7 @@
"""Datenträger und RAID-Gruppen aus dem Plugin Netbox-Utilities (netbox_utilities.Disk)."""
from django.apps import apps
from django.utils.formats import date_format
from django.utils.translation import gettext as _
from .blocks import EMPTY, H, KV, T
@@ -23,7 +25,7 @@ def _helpers():
def _date(value):
return value.strftime("%d.%m.%Y") if value else None
return date_format(value, "SHORT_DATE_FORMAT") if value else None
def _slot(disk):
@@ -53,18 +55,18 @@ def disk_blocks(scope, opts):
by_device.setdefault(disk.device, []).append(disk)
show_installed = bool(opts.get("disk_install_date"))
headers = ["Steckplatz", "Status", "Datenträger", "Größe", "Seriennummer", "RAID"]
headers += ["Eingebaut"] * show_installed + ["Garantie bis", "Hinweise"]
headers = [_("Slot"), _("Status"), _("Disk"), _("Size"), _("Serial number"), "RAID"]
headers += [_("Installed")] * show_installed + [_("Warranty until"), _("Notes")]
blocks = []
for device, items in by_device.items():
slots = sum(b.slot_count for b in DiskBayLayout.objects.filter(device=device))
summary = helpers.disk_summary(items, slots)
blocks.append(H(2, device.name or str(device)))
blocks.append(KV([
("Steckplätze belegt", f"{summary['used']} / {slots}" if slots else summary["used"]),
("Rohkapazität", fmt(summary["raw_capacity_gb"])),
("Hot Spares", summary["spares"]),
("Defekt", summary["failed"]),
(_("Slots used"), f"{summary['used']} / {slots}" if slots else summary["used"]),
(_("Raw capacity"), fmt(summary["raw_capacity_gb"])),
(_("Hot spares"), summary["spares"]),
(_("Failed"), summary["failed"]),
]))
groups = list(RAIDGroup.objects.filter(device=device).order_by("name"))
@@ -81,7 +83,7 @@ def disk_blocks(scope, opts):
tolerated if tolerated is not None else EMPTY,
group.description,
])
blocks.append(T(["RAID-Gruppe", "Level", "Datenträger", "Nutzbar", "Ausfalltoleranz", "Beschreibung"], rows))
blocks.append(T([_("RAID group"), _("Level"), _("Disks"), _("Usable"), _("Fault tolerance"), _("Description")], rows))
rows = []
for d in items:
+9 -8
View File
@@ -12,6 +12,7 @@ from io import BytesIO
from django.apps import apps
from django.db.models import Q
from django.utils.html import escape
from django.utils.translation import gettext as _
from .blocks import H, IMAGES, KV, P, T
@@ -242,11 +243,11 @@ def floorplan_blocks(scope, opts):
blocks.append(
KV(
[
("Standort", plan.site),
("Lokation", plan.location),
("Mandant", plan.tenant),
("Raumgröße", f"{meters(plan.width)} × {meters(plan.depth)} m"),
("Beschreibung", plan.description),
(_("Site"), plan.site),
(_("Location"), plan.location),
(_("Tenant"), plan.tenant),
(_("Room size"), f"{meters(plan.width)} × {meters(plan.depth)} m"),
(_("Description"), plan.description),
]
)
)
@@ -263,15 +264,15 @@ def floorplan_blocks(scope, opts):
if svg or png:
blocks.append(IMAGES([(svg, "", png)], wide=True))
else:
blocks.append(P(f"Raumplan konnte nicht erzeugt werden: {error}"))
blocks.append(P(_("Floor plan could not be generated: %(error)s") % {"error": error}))
placed = [i for i in items if i.rack_id or i.device_id]
if placed and opts.get("floorplan_objects", True):
rows = []
for i in sorted(placed, key=lambda i: _text(i).lower()):
obj = i.rack or i.device
kind = "Rack" if i.rack_id else "Gerät"
kind = _("Rack") if i.rack_id else _("Device")
rows.append([obj.name or str(obj), kind, i.label if i.label and i.label != obj.name else None])
blocks.append(T(["Name", "Art", "Beschriftung im Plan"], rows))
blocks.append(T([_("Name"), _("Type"), _("Label in plan")], rows))
if plan.comments:
blocks.append(P(plan.comments))
return blocks
+45 -43
View File
@@ -1,4 +1,5 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from dcim.models import DeviceRole, DeviceType, Location, Site
from netbox.plugins import get_plugin_config
from tenancy.models import Tenant, TenantGroup
@@ -9,98 +10,99 @@ from .models import BrandingProfile, TopologySymbol
from .sections import DEFAULT_DEVICE_COLUMNS, DEVICE_COLUMNS, SECTIONS
from .symbols import KIND_CHOICES
FORMAT_CHOICES = (("pdf", "PDF"), ("docx", "Word"), ("html", "HTML-Vorschau"))
FORMAT_CHOICES = (("pdf", "PDF"), ("docx", "Word"), ("html", _("HTML preview")))
class ScopeSelectForm(forms.Form):
site = DynamicModelChoiceField(queryset=Site.objects.all(), required=False, label="Standort")
location = DynamicModelChoiceField(queryset=Location.objects.all(), required=False, label="Lokation")
tenant = DynamicModelChoiceField(queryset=Tenant.objects.all(), required=False, label="Mandant")
tenantgroup = DynamicModelChoiceField(queryset=TenantGroup.objects.all(), required=False, label="Mandantengruppe")
site = DynamicModelChoiceField(queryset=Site.objects.all(), required=False, label=_("Site"))
location = DynamicModelChoiceField(queryset=Location.objects.all(), required=False, label=_("Location"))
tenant = DynamicModelChoiceField(queryset=Tenant.objects.all(), required=False, label=_("Tenant"))
tenantgroup = DynamicModelChoiceField(queryset=TenantGroup.objects.all(), required=False, label=_("Tenant group"))
def clean(self):
data = super().clean()
chosen = [(k, v) for k, v in data.items() if v]
if len(chosen) != 1:
raise forms.ValidationError("Bitte genau einen Scope auswählen.")
raise forms.ValidationError(_("Select exactly one scope."))
data["kind"], data["obj"] = chosen[0]
return data
class ExportForm(forms.Form):
format = forms.ChoiceField(choices=FORMAT_CHOICES, initial="pdf", label="Format")
title = forms.CharField(max_length=200, label="Titel")
subtitle = forms.CharField(max_length=200, required=False, label="Untertitel")
author = forms.CharField(max_length=100, required=False, label="Erstellt von")
branding = forms.ChoiceField(choices=(), label="Design / Firma")
format = forms.ChoiceField(choices=FORMAT_CHOICES, initial="pdf", label=_("Format"))
title = forms.CharField(max_length=200, label=_("Title"))
subtitle = forms.CharField(max_length=200, required=False, label=_("Subtitle"))
author = forms.CharField(max_length=100, required=False, label=_("Created by"))
branding = forms.ChoiceField(choices=(), label=_("Design / company"))
sections = forms.MultipleChoiceField(
choices=[(s.key, s.label) for s in SECTIONS.values()],
initial=[s.key for s in SECTIONS.values() if s.default],
widget=forms.CheckboxSelectMultiple,
label="Inhalte",
label=_("Contents"),
)
roles = forms.ModelMultipleChoiceField(
queryset=DeviceRole.objects.none(), required=False, widget=forms.CheckboxSelectMultiple, label="Geräterollen"
queryset=DeviceRole.objects.none(), required=False, widget=forms.CheckboxSelectMultiple, label=_("Device roles")
)
device_columns = forms.MultipleChoiceField(
choices=[(k, v[0]) for k, v in DEVICE_COLUMNS.items()],
initial=DEFAULT_DEVICE_COLUMNS,
required=False,
widget=forms.CheckboxSelectMultiple,
label="Gerätespalten",
label=_("Device columns"),
)
group_by_site = forms.BooleanField(required=False, initial=True, label="Geräte nach Standort gruppieren")
group_by_site = forms.BooleanField(required=False, initial=True, label=_("Group devices by site"))
disk_install_date = forms.BooleanField(required=False, initial=False, label="Einbaudatum der Datenträger anzeigen")
disk_install_date = forms.BooleanField(required=False, initial=False, label=_("Show disk installation date"))
rack_svg = forms.BooleanField(required=False, initial=True, label="Rack-Ansichten (SVG) einbetten")
rack_images = forms.BooleanField(required=False, initial=False, label="Gerätebilder anzeigen (wie in NetBox)")
rack_svg = forms.BooleanField(required=False, initial=True, label=_("Embed rack elevations (SVG)"))
rack_images = forms.BooleanField(required=False, initial=False, label=_("Show device images (as in NetBox)"))
rack_faces = forms.MultipleChoiceField(
choices=(("front", "Vorderseite"), ("rear", "Rückseite")),
choices=(("front", _("Front")), ("rear", _("Rear"))),
initial=["front"],
required=False,
widget=forms.CheckboxSelectMultiple,
label="Rack-Seiten",
label=_("Rack faces"),
)
rack_devices = forms.BooleanField(required=False, initial=True, label="Geräteliste je Rack")
rack_pagebreak = forms.BooleanField(required=False, initial=True, label="Seitenumbruch nach jedem Rack")
rack_photos = forms.MultipleChoiceField(choices=(), required=False, widget=forms.CheckboxSelectMultiple, label="Rack-Fotos")
rack_devices = forms.BooleanField(required=False, initial=True, label=_("Device list per rack"))
rack_pagebreak = forms.BooleanField(required=False, initial=True, label=_("Page break after each rack"))
rack_photos = forms.MultipleChoiceField(choices=(), required=False, widget=forms.CheckboxSelectMultiple, label=_("Rack photos"))
topo_details = forms.MultipleChoiceField(
choices=(("model", "Modell"), ("primary_ip", "Management-IP"), ("ports", "Ports an Verbindungen")),
choices=(("model", _("Model")), ("primary_ip", _("Management IP")), ("ports", _("Ports on links"))),
initial=["primary_ip"],
required=False,
widget=forms.CheckboxSelectMultiple,
label="Beschriftung",
label=_("Labels"),
)
topo_scope = forms.MultipleChoiceField(
choices=(
("site", "Gesamtes Netzwerk (je Standort)"),
("locations", "Lokationsübersicht (Verbindungen zwischen Lokationen)"),
("rack", "Je Rack"),
("site", _("Whole network (per site)")),
("locations", _("Location overview (connections between locations)")),
("locations_all", _("Cross-site location overview (all locations in one diagram)")),
("rack", _("Per rack")),
),
initial=["site"],
required=False,
widget=forms.CheckboxSelectMultiple,
label="Umfang",
label=_("Scope"),
)
topo_external = forms.BooleanField(
required=False, initial=True, label="Provider-Leitungen & Geräte außerhalb anzeigen"
required=False, initial=True, label=_("Show provider circuits and devices outside the scope")
)
topo_isolated = forms.BooleanField(required=False, initial=False, label="Unverkabelte Geräte anzeigen")
topo_isolated = forms.BooleanField(required=False, initial=False, label=_("Show uncabled devices"))
ip_versions = forms.MultipleChoiceField(
choices=(("4", "IPv4"), ("6", "IPv6")),
initial=["4", "6"],
required=False,
widget=forms.CheckboxSelectMultiple,
label="IP-Versionen",
label=_("IP versions"),
)
include_empty = forms.BooleanField(required=False, label="Leere Abschnitte trotzdem aufführen")
include_secrets = forms.BooleanField(required=False, label="Geheimnisse (z.B. WLAN-PSK) mit exportieren")
include_empty = forms.BooleanField(required=False, label=_("List empty sections anyway"))
include_secrets = forms.BooleanField(required=False, label=_("Include secrets (e.g. Wi-Fi PSK)"))
def __init__(self, *args, scope=None, **kwargs):
super().__init__(*args, **kwargs)
@@ -124,7 +126,7 @@ class ExportForm(forms.Form):
roles = DeviceRole.objects.filter(pk__in=role_ids).order_by("name")
self.fields["roles"].queryset = roles
self.fields["roles"].initial = [r.pk for r in roles]
self.fields["title"].initial = f"Netzwerkdokumentation {scope.obj}"
self.fields["title"].initial = _("Network documentation %(name)s") % {"name": scope.obj}
self.fields["subtitle"].initial = f"{scope.label}: {scope.obj}"
if not get_plugin_config("netbox_customer_export", "allow_secrets"):
del self.fields["include_secrets"]
@@ -155,10 +157,10 @@ class BrandingProfileForm(forms.ModelForm):
"extra_css": forms.Textarea(attrs={"rows": 4, "class": "form-control font-monospace"}),
}
help_texts = {
"is_default": "Wird im Exportformular vorausgewählt.",
"logo": "PNG oder JPG, erscheint auf dem Deckblatt.",
"docx_template": ".docx oder .dotx: Formatvorlagen, Kopf-/Fußzeile und Ränder werden übernommen.",
"docx_table_style": "Name wie in Word angezeigt, z.B. Gitternetztabelle 4 – Akzent 1. Leer = eigene Einfärbung.",
"is_default": _("Preselected in the export form."),
"logo": _("PNG or JPG, shown on the cover page."),
"docx_template": _(".docx or .dotx: styles, header/footer and margins are applied."),
"docx_table_style": _("Name as shown in Word, e.g. Grid Table 4 – Accent 1. Empty = own colouring."),
}
def __init__(self, *args, **kwargs):
@@ -172,17 +174,17 @@ class BrandingProfileForm(forms.ModelForm):
class TopologySymbolForm(forms.ModelForm):
device_type = DynamicModelChoiceField(queryset=DeviceType.objects.all(), required=False, label="Gerätetyp")
role = DynamicModelChoiceField(queryset=DeviceRole.objects.all(), required=False, label="Geräterolle")
device_type = DynamicModelChoiceField(queryset=DeviceType.objects.all(), required=False, label=_("Device type"))
role = DynamicModelChoiceField(queryset=DeviceRole.objects.all(), required=False, label=_("Device role"))
kind = forms.ChoiceField(
choices=[("", "Automatisch")] + KIND_CHOICES, required=False, widget=forms.RadioSelect, label="Symbol"
choices=[("", _("Automatic"))] + KIND_CHOICES, required=False, widget=forms.RadioSelect, label=_("Symbol")
)
class Meta:
model = TopologySymbol
fields = ("device_type", "role", "kind", "icon")
help_texts = {
"icon": "PNG, JPG oder GIF, am besten quadratisch mit transparentem Hintergrund. Ersetzt das gewählte Symbol.",
"icon": _("PNG, JPG or GIF, ideally square with a transparent background. Replaces the selected symbol."),
}
def __init__(self, *args, **kwargs):
+2 -1
View File
@@ -1,5 +1,6 @@
"""CPU & RAM aus dem Plugin Netbox-Utilities (netbox_utilities.DeviceHardware)."""
from django.apps import apps
from django.utils.translation import gettext as _
def is_installed():
@@ -38,7 +39,7 @@ def cpu_text(device):
if not hw or not hw.cpu_id:
return None
cores, threads = cores_threads(hw)
return f"{hw.cpu_display}\n{cores} Kerne / {threads} Threads"
return f"{hw.cpu_display}\n" + _("%(cores)s cores / %(threads)s threads") % {"cores": cores, "threads": threads}
def ram_text(device):
+30 -19
View File
@@ -4,6 +4,9 @@ from itertools import groupby
from django.apps import apps
from django.db.models import Q
from django.utils.formats import date_format
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from .blocks import EMPTY, H, T
@@ -55,29 +58,37 @@ def licenses_for_scope(scope):
def _validity(lic, today):
"""(Laufzeit-Text, Status-Text)."""
if lic.lifetime:
return "unbefristet", "aktiv"
start = lic.start_date.strftime("%d.%m.%Y") if lic.start_date else ""
end = lic.expiration_date.strftime("%d.%m.%Y") if lic.expiration_date else ""
period = f"{start} – {end}" if start and end else (f"bis {end}" if end else (f"ab {start}" if start else EMPTY))
return _("unlimited"), _("active")
start = date_format(lic.start_date, "SHORT_DATE_FORMAT") if lic.start_date else ""
end = date_format(lic.expiration_date, "SHORT_DATE_FORMAT") if lic.expiration_date else ""
if start and end:
period = f"{start} – {end}"
elif end:
period = _("until %(date)s") % {"date": end}
elif start:
period = _("from %(date)s") % {"date": start}
else:
period = EMPTY
if lic.renewal_interval and lic.renewal_interval_unit:
if lic.renewal_interval == 1:
every = {"days": "täglich", "months": "monatlich", "years": "jährlich"}.get(lic.renewal_interval_unit, "")
else:
unit = {"days": "Tage", "months": "Monate", "years": "Jahre"}.get(lic.renewal_interval_unit, lic.renewal_interval_unit)
every = f"alle {lic.renewal_interval} {unit}"
period += f" (Verlängerung {every})"
n = lic.renewal_interval
every = {
"days": ngettext("daily", "every %(n)d days", n),
"months": ngettext("monthly", "every %(n)d months", n),
"years": ngettext("yearly", "every %(n)d years", n),
}.get(lic.renewal_interval_unit, f"{n} {lic.renewal_interval_unit}")
period += " " + _("(renewal %(interval)s)") % {"interval": every % {"n": n}}
if not lic.expiration_date:
return period, "aktiv"
return period, _("active")
days = (lic.expiration_date - today).days
if days < 0:
return period, "abgelaufen"
return period, _("expired")
if days <= SOON_DAYS:
return period, f"läuft in {days} Tagen ab"
return period, "aktiv"
return period, ngettext("expires in %(days)d day", "expires in %(days)d days", days) % {"days": days}
return period, _("active")
def _support(value):
return {True: "Ja", False: "Nein"}.get(value, EMPTY)
return {True: _("Yes"), False: _("No")}.get(value, EMPTY)
def _installed_on(lic):
@@ -85,7 +96,7 @@ def _installed_on(lic):
if not inst:
return None
target = inst.device or inst.virtualmachine or inst.cluster
kind = "Gerät" if inst.device_id else ("VM" if inst.virtualmachine_id else "Cluster")
kind = _("Device") if inst.device_id else (_("VM") if inst.virtualmachine_id else _("Cluster"))
return f"{target} ({kind})" if target else None
@@ -96,9 +107,9 @@ def slm_blocks(scope, opts):
return []
today = date.today()
show_key = bool(opts.get("include_secrets"))
headers = ["Lizenz", "Produkt / Version", "Typ", "Anzahl", "Laufzeit", "Status", "Support", "Installiert auf", "Mandant"]
headers = [_("License"), _("Product / version"), _("Type"), _("Quantity"), _("Term"), _("Status"), _("Support"), _("Installed on"), _("Tenant")]
if show_key:
headers.append("Lizenzschlüssel")
headers.append(_("License key"))
blocks = []
by_manufacturer = sorted(qs, key=lambda lic: (str(lic.software_product.manufacturer or "~"), str(lic.software_product), lic.name))
@@ -121,6 +132,6 @@ def slm_blocks(scope, opts):
if show_key:
row.append(lic.license_key)
rows.append(row)
blocks.append(H(2, str(manufacturer) if manufacturer else "Ohne Hersteller"))
blocks.append(H(2, str(manufacturer) if manufacturer else _("No manufacturer")))
blocks.append(T(headers, rows))
return blocks
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
# Generated by Django 6.1.2 on 2026-10-26 20:23
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_customer_export', '0002_topologysymbol'),
]
operations = [
migrations.AlterField(
model_name='brandingprofile',
name='accent_color',
field=models.CharField(default='2E75B6', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
),
migrations.AlterField(
model_name='brandingprofile',
name='footer_text',
field=models.CharField(blank=True, default="Confidential – for the customer's internal use only", max_length=300),
),
migrations.AlterField(
model_name='brandingprofile',
name='header_text_color',
field=models.CharField(default='FFFFFF', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
),
migrations.AlterField(
model_name='brandingprofile',
name='label_bg_color',
field=models.CharField(default='DEEAF6', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
),
migrations.AlterField(
model_name='brandingprofile',
name='primary_color',
field=models.CharField(default='1F4E79', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
),
migrations.AlterField(
model_name='brandingprofile',
name='stripe_color',
field=models.CharField(default='F3F7FB', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
),
]
+29 -28
View File
@@ -1,8 +1,9 @@
from django.core.validators import FileExtensionValidator, MaxValueValidator, MinValueValidator, RegexValidator
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
hex_color = RegexValidator(r"^[0-9A-Fa-f]{6}$", "Hex-Farbe ohne # erwartet, z.B. 1F4E79")
hex_color = RegexValidator(r"^[0-9A-Fa-f]{6}$", _("Expected a hex colour without #, e.g. 1F4E79"))
def _color(default, verbose_name):
@@ -12,36 +13,36 @@ def _color(default, verbose_name):
class BrandingProfile(models.Model):
"""In NetBox gepflegtes Design-Profil (Alternative/Ergänzung zu PLUGINS_CONFIG['brandings'])."""
name = models.CharField(max_length=100, unique=True, verbose_name="Name")
is_default = models.BooleanField(default=False, verbose_name="Standardprofil")
company_name = models.CharField(max_length=200, blank=True, verbose_name="Firmenname")
name = models.CharField(max_length=100, unique=True, verbose_name=_("Name"))
is_default = models.BooleanField(default=False, verbose_name=_("Default profile"))
company_name = models.CharField(max_length=200, blank=True, verbose_name=_("Company name"))
footer_text = models.CharField(
max_length=300, blank=True, default="Vertraulich – nur für den internen Gebrauch des Kunden", verbose_name="Fußzeile"
max_length=300, blank=True, default="Confidential – for the customer's internal use only", verbose_name=_("Footer")
)
logo = models.ImageField(upload_to="customer-export/logos/", blank=True, verbose_name="Logo")
primary_color = _color("1F4E79", "Primärfarbe")
accent_color = _color("2E75B6", "Akzentfarbe")
header_text_color = _color("FFFFFF", "Schrift Tabellenkopf")
label_bg_color = _color("DEEAF6", "Hintergrund Beschriftungen")
stripe_color = _color("F3F7FB", "Zebrastreifen")
font_family = models.CharField(max_length=100, default="Calibri", verbose_name="Schriftart")
logo = models.ImageField(upload_to="customer-export/logos/", blank=True, verbose_name=_("Logo"))
primary_color = _color("1F4E79", _("Primary colour"))
accent_color = _color("2E75B6", _("Accent colour"))
header_text_color = _color("FFFFFF", _("Table header text"))
label_bg_color = _color("DEEAF6", _("Label background"))
stripe_color = _color("F3F7FB", _("Row stripes"))
font_family = models.CharField(max_length=100, default="Calibri", verbose_name=_("Font"))
font_size = models.PositiveSmallIntegerField(
default=10, validators=[MinValueValidator(7), MaxValueValidator(16)], verbose_name="Schriftgröße (pt)"
default=10, validators=[MinValueValidator(7), MaxValueValidator(16)], verbose_name=_("Font size (pt)")
)
docx_template = models.FileField(
upload_to="customer-export/templates/",
blank=True,
validators=[FileExtensionValidator(["docx", "dotx"])],
verbose_name="Word-Vorlage",
verbose_name=_("Word template"),
)
docx_table_style = models.CharField(max_length=100, blank=True, verbose_name="Tabellenformatvorlage (Word)")
extra_css = models.TextField(blank=True, verbose_name="Zusätzliches CSS (PDF/HTML)")
docx_table_style = models.CharField(max_length=100, blank=True, verbose_name=_("Table style (Word)"))
extra_css = models.TextField(blank=True, verbose_name=_("Additional CSS (PDF/HTML)"))
last_updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ("-is_default", "name")
verbose_name = "Branding-Profil"
verbose_name_plural = "Branding-Profile"
verbose_name = _("branding profile")
verbose_name_plural = _("branding profiles")
def __str__(self):
return self.name
@@ -80,19 +81,19 @@ class TopologySymbol(models.Model):
"""Topologie-Symbol für einen Gerätetyp oder eine Geräterolle (Gerätetyp hat Vorrang)."""
device_type = models.OneToOneField(
"dcim.DeviceType", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name="Gerätetyp"
"dcim.DeviceType", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name=_("Device type")
)
role = models.OneToOneField(
"dcim.DeviceRole", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name="Geräterolle"
"dcim.DeviceRole", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name=_("Device role")
)
kind = models.CharField(max_length=20, blank=True, verbose_name="Symbol")
icon = models.ImageField(upload_to="customer-export/symbols/", blank=True, verbose_name="Eigenes Icon")
kind = models.CharField(max_length=20, blank=True, verbose_name=_("Symbol"))
icon = models.ImageField(upload_to="customer-export/symbols/", blank=True, verbose_name=_("Custom icon"))
last_updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ("device_type__model", "role__name")
verbose_name = "Topologie-Symbol"
verbose_name_plural = "Topologie-Symbole"
verbose_name = _("topology symbol")
verbose_name_plural = _("topology symbols")
def __str__(self):
return str(self.device_type or self.role)
@@ -102,17 +103,17 @@ class TopologySymbol(models.Model):
@property
def target_label(self):
return "Gerätetyp" if self.device_type_id else "Geräterolle"
return _("Device type") if self.device_type_id else _("Device role")
def get_kind_display(self):
from .symbols import KIND_CHOICES
return dict(KIND_CHOICES).get(self.kind, "Automatisch")
return dict(KIND_CHOICES).get(self.kind, _("Automatic"))
def clean(self):
from django.core.exceptions import ValidationError
if bool(self.device_type_id) == bool(self.role_id):
raise ValidationError("Bitte genau einen Gerätetyp oder eine Geräterolle wählen.")
raise ValidationError(_("Select exactly one device type or one device role."))
if not self.kind and not self.icon:
raise ValidationError("Bitte ein Symbol wählen oder ein eigenes Icon hochladen.")
raise ValidationError(_("Select a symbol or upload a custom icon."))
+18 -7
View File
@@ -1,19 +1,20 @@
from netbox.plugins import PluginMenuButton, PluginMenuItem
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenu, PluginMenuButton, PluginMenuItem
menu_items = (
_items = (
PluginMenuItem(
link="plugins:netbox_customer_export:select",
link_text="Kundendokumentation",
link_text=_("Customer Documentation"),
permissions=["dcim.view_site"],
),
PluginMenuItem(
link="plugins:netbox_customer_export:symbol_list",
link_text="Topologie-Symbole",
link_text=_("Topology Symbols"),
permissions=["netbox_customer_export.view_topologysymbol"],
buttons=(
PluginMenuButton(
link="plugins:netbox_customer_export:symbol_add",
title="Hinzufügen",
title=_("Add"),
icon_class="mdi mdi-plus-thick",
permissions=["netbox_customer_export.add_topologysymbol"],
),
@@ -21,15 +22,25 @@ menu_items = (
),
PluginMenuItem(
link="plugins:netbox_customer_export:branding_list",
link_text="Branding-Profile",
link_text=_("Branding Profiles"),
permissions=["netbox_customer_export.view_brandingprofile"],
buttons=(
PluginMenuButton(
link="plugins:netbox_customer_export:branding_add",
title="Hinzufügen",
title=_("Add"),
icon_class="mdi mdi-plus-thick",
permissions=["netbox_customer_export.add_brandingprofile"],
),
),
),
)
# Eigener Eintrag im obersten Navigationsmenü statt unter „Plugins“
menu = PluginMenu(
label=_("Customer Export"),
groups=(
(_("Export"), _items[:1]),
(_("Settings"), _items[1:]),
),
icon_class="mdi mdi-file-document-multiple-outline",
)
+4 -1
View File
@@ -1,3 +1,6 @@
from django.utils.translation import gettext as _
class MissingDependency(Exception):
pass
@@ -18,6 +21,6 @@ def render(doc, fmt, request=None):
try:
from weasyprint import HTML
except (ImportError, OSError) as e:
raise MissingDependency(f"PDF-Export benötigt WeasyPrint (pip install weasyprint + Pango): {e}")
raise MissingDependency(_("PDF export requires WeasyPrint (pip install weasyprint + Pango): %(error)s") % {"error": e})
base_url = request.build_absolute_uri("/") if request else None
return HTML(string=html, base_url=base_url).write_pdf(), "application/pdf", "pdf"
+8 -6
View File
@@ -2,6 +2,8 @@ import re
import zipfile
from io import BytesIO
from django.utils.translation import gettext as _
from . import MissingDependency
DOTX_TYPE = b"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"
@@ -52,7 +54,7 @@ def render_docx(doc):
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor
except ImportError as e:
raise MissingDependency(f"Word-Export benötigt python-docx (pip install python-docx cairosvg): {e}")
raise MissingDependency(_("Word export requires python-docx (pip install python-docx cairosvg): %(error)s") % {"error": e})
b = doc.branding
primary = RGBColor.from_string(b["primary_color"])
@@ -62,7 +64,7 @@ def render_docx(doc):
try:
d = _load_template(template)
except (OSError, KeyError, zipfile.BadZipFile) as e:
raise MissingDependency(f"Word-Vorlage {template!r} konnte nicht geladen werden: {e}")
raise MissingDependency(_("Word template %(path)r could not be loaded: %(error)s") % {"path": template, "error": e})
else:
# Ohne Vorlage: Standarddokument mit Farben/Schrift aus dem Branding
d = Docx()
@@ -98,7 +100,7 @@ def render_docx(doc):
meta = doc.meta
if b.get("logo_path"):
d.add_picture(b["logo_path"], width=Cm(5))
for _ in range(6):
for _blank in range(6):
d.add_paragraph()
title = d.add_paragraph()
run = title.add_run(doc.title)
@@ -108,13 +110,13 @@ def render_docx(doc):
d.add_paragraph().add_run(doc.subtitle).font.size = Pt(16)
d.add_paragraph()
info = d.add_paragraph()
for label, value in (("Stand", meta.get("date")), ("Erstellt von", meta.get("author")), ("", b.get("company_name"))):
for label, value in ((_("As of"), meta.get("date")), (_("Created by"), meta.get("author")), ("", b.get("company_name"))):
if value:
info.add_run(f"{label + ': ' if label else ''}{value}\n")
d.add_page_break()
# Inhaltsverzeichnis (wird beim Öffnen in Word aktualisiert)
d.add_heading("Inhaltsverzeichnis", level=1)
d.add_heading(_("Table of contents"), level=1)
fld = OxmlElement("w:fldSimple")
fld.set(qn("w:instr"), 'TOC \\o "1-2" \\h \\z \\u')
d.add_paragraph()._p.append(fld)
@@ -265,7 +267,7 @@ def render_docx(doc):
width = min(width, 9 * px_w / px_h) # Hochformat-Fotos auf max. 9 cm Höhe begrenzen
cell.add_run().add_picture(BytesIO(png), width=Cm(width))
else:
cell.add_run("(Rack-Grafik nicht verfügbar)")
cell.add_run(_("(rack graphic not available)"))
cap = t.cell(1, i).paragraphs[0]
cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
if img["caption"]:
+5 -4
View File
@@ -1,5 +1,6 @@
"""Ermittelt, welche Objekte zu einem Export-Scope (Standort, Lokation, Mandant, Mandantengruppe) gehören."""
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from circuits.models import Circuit
from dcim.models import Device, Location, PowerFeed, Rack, Site
@@ -16,10 +17,10 @@ SCOPE_MODELS = {
}
SCOPE_LABELS = {
"site": "Standort",
"location": "Lokation",
"tenant": "Mandant",
"tenantgroup": "Mandantengruppe",
"site": _("Site"),
"location": _("Location"),
"tenant": _("Tenant"),
"tenantgroup": _("Tenant group"),
}
NONE = Q(pk__in=[])
+140 -132
View File
@@ -5,6 +5,8 @@ from itertools import groupby
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy, ngettext
from netbox.plugins import get_plugin_config
from .blocks import EMPTY, H, IMAGES, KV, LANDSCAPE, P, PAGEBREAK, REF, T, get
@@ -66,27 +68,27 @@ def num(value):
def _rack_pos(d, o=None):
if not d.rack:
return None
pos = f" / HE {num(d.position)}" if d.position else ""
pos = " / " + _("U %(u)s") % {"u": num(d.position)} if d.position else ""
return f"{d.rack}{pos}"
DEVICE_COLUMNS = OrderedDict(
[
("name", ("Name", lambda d, o: d.name or str(d))),
("model", ("Hersteller / Modell", lambda d, o: f"{d.device_type.manufacturer} {d.device_type.model}")),
("site", ("Standort", lambda d, o: d.site)),
("location", ("Lokation", lambda d, o: d.location)),
("rack", ("Rack / HE", _rack_pos)),
("status", ("Status", lambda d, o: d.get_status_display())),
("platform", ("Plattform / OS", lambda d, o: d.platform)),
("primary_ip", ("Management-IP", lambda d, o: primary_ips(d, o))),
("oob_ip", ("OOB-IP", lambda d, o: ip_text([d.oob_ip], o))),
("serial", ("Seriennummer", lambda d, o: d.serial)),
("cpu", ("CPU", lambda d, o: hardware_utilities.cpu_text(d))),
("ram", ("RAM", lambda d, o: hardware_utilities.ram_text(d))),
("asset_tag", ("Inventarnr.", lambda d, o: d.asset_tag)),
("tenant", ("Mandant", lambda d, o: d.tenant)),
("description", ("Beschreibung", lambda d, o: d.description)),
("name", (gettext_lazy("Name"), lambda d, o: d.name or str(d))),
("model", (gettext_lazy("Manufacturer / model"), lambda d, o: f"{d.device_type.manufacturer} {d.device_type.model}")),
("site", (gettext_lazy("Site"), lambda d, o: d.site)),
("location", (gettext_lazy("Location"), lambda d, o: d.location)),
("rack", (gettext_lazy("Rack / U"), _rack_pos)),
("status", (gettext_lazy("Status"), lambda d, o: d.get_status_display())),
("platform", (gettext_lazy("Platform / OS"), lambda d, o: d.platform)),
("primary_ip", (gettext_lazy("Management IP"), lambda d, o: primary_ips(d, o))),
("oob_ip", (gettext_lazy("OOB IP"), lambda d, o: ip_text([d.oob_ip], o))),
("serial", (gettext_lazy("Serial number"), lambda d, o: d.serial)),
("cpu", (gettext_lazy("CPU"), lambda d, o: hardware_utilities.cpu_text(d))),
("ram", (gettext_lazy("RAM"), lambda d, o: hardware_utilities.ram_text(d))),
("asset_tag", (gettext_lazy("Asset tag"), lambda d, o: d.asset_tag)),
("tenant", (gettext_lazy("Tenant"), lambda d, o: d.tenant)),
("description", (gettext_lazy("Description"), lambda d, o: d.description)),
]
)
DEFAULT_DEVICE_COLUMNS = ["name", "model", "location", "rack", "primary_ip", "serial"]
@@ -97,44 +99,44 @@ def _device_table(devices, columns, opts):
return T([c[0] for c in cols], [[c[1](d, opts) for c in cols] for d in devices])
def _empty(opts, blocks, text="Keine Einträge vorhanden."):
def _empty(opts, blocks, text=None):
if opts.get("include_empty"):
blocks.append(P(text))
blocks.append(P(text or _("No entries.")))
return blocks
return []
# --- Abschnitte -------------------------------------------------------------
@section("overview", "Übersicht & Standortdaten", "Allgemein", hint="Kennzahlen, Adressen, Lokationsbaum")
@section("overview", gettext_lazy("Overview & site data"), gettext_lazy("General"), hint=gettext_lazy("Key figures, addresses, location tree"))
def overview(scope, opts):
blocks = [H(1, "Übersicht")]
blocks = [H(1, _("Overview"))]
counts = [
("Standorte", scope.sites().count()),
("Racks", scope.racks().count()),
("Geräte", scope.devices().count()),
("Virtuelle Maschinen", scope.virtual_machines().count()),
("Präfixe", scope.prefixes().count()),
("VLANs", scope.vlans().count()),
("Leitungen", scope.circuits().count()),
(_("Sites"), scope.sites().count()),
(_("Racks"), scope.racks().count()),
(_("Devices"), scope.devices().count()),
(_("Virtual machines"), scope.virtual_machines().count()),
(_("Prefixes"), scope.prefixes().count()),
(_("VLANs"), scope.vlans().count()),
(_("Circuits"), scope.circuits().count()),
]
blocks.append(KV([(f"{scope.label}", scope.obj)] + counts))
if getattr(scope.obj, "description", ""):
blocks.append(P(scope.obj.description))
for site in scope.sites().select_related("region", "group", "tenant"):
blocks.append(H(2, f"Standort {site.name}"))
blocks.append(H(2, _("Site %(name)s") % {"name": site.name}))
blocks.append(
KV(
[
("Status", site.get_status_display()),
("Region", site.region),
("Mandant", site.tenant),
("Einrichtung", site.facility),
("Anschrift", site.physical_address),
("Lieferanschrift", site.shipping_address),
("Zeitzone", site.time_zone),
("Beschreibung", site.description),
(_("Status"), site.get_status_display()),
(_("Region"), site.region),
(_("Tenant"), site.tenant),
(_("Facility"), site.facility),
(_("Physical address"), site.physical_address),
(_("Shipping address"), site.shipping_address),
(_("Time zone"), site.time_zone),
(_("Description"), site.description),
]
)
)
@@ -142,20 +144,20 @@ def overview(scope, opts):
if locs.exists():
blocks.append(
T(
["Lokation", "Übergeordnet", "Status", "Beschreibung"],
[_("Location"), _("Parent"), _("Status"), _("Description")],
[[(" " * loc.level) + loc.name, loc.parent, loc.get_status_display(), loc.description] for loc in locs],
)
)
return blocks
@section("contacts", "Ansprechpartner", "Allgemein", hint="Kontakte an Standorten, Lokationen, Mandanten")
@section("contacts", gettext_lazy("Contacts"), gettext_lazy("General"), hint=gettext_lazy("Contacts of sites, locations, tenants"))
def contacts(scope, opts):
ContactAssignment = apps.get_model("tenancy", "ContactAssignment")
targets = [
(scope.sites(), "Standort"),
(scope.location_objects(), "Lokation"),
(scope.tenant_objects(), "Mandant"),
(scope.sites(), _("Site")),
(scope.location_objects(), _("Location")),
(scope.tenant_objects(), _("Tenant")),
]
rows = []
for qs, label in targets:
@@ -167,41 +169,41 @@ def contacts(scope, opts):
rows.append(
[f"{label}: {a.object}", a.contact.name, a.role, a.get_priority_display(), a.contact.phone, a.contact.email]
)
blocks = [H(1, "Ansprechpartner")]
blocks = [H(1, _("Contacts"))]
if not rows:
return _empty(opts, blocks)
blocks.append(T(["Zuordnung", "Name", "Rolle", "Priorität", "Telefon", "E-Mail"], rows))
blocks.append(T([_("Assigned to"), _("Name"), _("Role"), _("Priority"), _("Phone"), _("Email")], rows))
return blocks
@section("racks", "Racks", "Infrastruktur", hint="Nach Standort & Lokation, mit Rack-Ansicht")
@section("racks", gettext_lazy("Racks"), gettext_lazy("Infrastructure"), hint=gettext_lazy("By site & location, with rack elevation"))
def racks(scope, opts):
qs = (
scope.racks()
.select_related("site", "location", "role", "tenant", "rack_type")
.order_by("site__name", "location__name", "name")
)
blocks = [H(1, "Racks")]
blocks = [H(1, _("Racks"))]
if not qs.exists():
return _empty(opts, blocks)
photos = _rack_photos(scope, opts)
for site, site_racks in groupby(qs, key=lambda r: r.site):
blocks.append(H(2, f"Standort {site}"))
blocks.append(H(2, _("Site %(name)s") % {"name": site}))
for location, loc_racks in groupby(site_racks, key=lambda r: r.location):
blocks.append(H(3, f"Lokation {location}" if location else "Ohne Lokation"))
blocks.append(H(3, _("Location %(name)s") % {"name": location} if location else _("No location")))
for rack in loc_racks:
rack_heading = H(4, f"Rack {rack.name}")
rack_heading = H(4, _("Rack %(name)s") % {"name": rack.name})
blocks.append(rack_heading)
blocks.append(
KV(
[
("Status", rack.get_status_display()),
("Rolle", rack.role),
("Typ", rack.rack_type),
("Höhe", f"{rack.u_height} HE"),
("Facility-ID", rack.facility_id),
("Mandant", rack.tenant),
("Beschreibung", rack.description),
(_("Status"), rack.get_status_display()),
(_("Role"), rack.role),
(_("Type"), rack.rack_type),
(_("Height"), _("%(u)s U") % {"u": rack.u_height}),
(_("Facility ID"), rack.facility_id),
(_("Tenant"), rack.tenant),
(_("Description"), rack.description),
]
)
)
@@ -212,7 +214,7 @@ def racks(scope, opts):
)
with_images = bool(opts.get("rack_images"))
for face in opts.get("rack_faces") or ["front"]:
caption = "Vorderseite" if face == "front" else "Rückseite"
caption = _("Front") if face == "front" else _("Rear")
svg, svg_error = render_rack_svg(rack, face, scope.user, images=with_images, devices=rack_devs)
png = None
# PNG wird für Word gebraucht (falls kein cairosvg) und ersetzt ein fehlgeschlagenes SVG
@@ -224,7 +226,7 @@ def racks(scope, opts):
if svg or png:
images.append((svg, caption, png))
else:
errors.append(f"Rack-Ansicht ({caption}) konnte nicht erzeugt werden: {svg_error}")
errors.append(_("Rack elevation (%(face)s) could not be created: %(error)s") % {"face": caption, "error": svg_error})
if images:
blocks.append(IMAGES(images))
blocks += [P(e) for e in errors]
@@ -233,7 +235,7 @@ def racks(scope, opts):
if devs.exists():
blocks.append(
T(
["HE", "Gerät", "Hersteller / Modell", "Seite"],
[_("U"), _("Device"), _("Manufacturer / model"), _("Face")],
[
[num(d.position) if d.position else EMPTY, d.name, f"{d.device_type.manufacturer} {d.device_type.model}", d.get_face_display() if d.face else EMPTY]
for d in devs
@@ -270,20 +272,24 @@ def _photo_appendix(opts, rack, rack_heading, atts):
return []
appendix = opts.setdefault("_appendix", [])
if not appendix:
appendix.append(H(1, "Anhang: Rack-Fotos"))
appendix.append(H(1, _("Appendix: rack photos")))
where = " / ".join(str(x) for x in (rack.site, rack.location) if x)
heading = H(2, f"Rack {rack.name}" + (f" ({where})" if where else ""))
heading = H(2, _("Rack %(name)s") % {"name": rack.name} + (f" ({where})" if where else ""))
appendix.append(heading)
for i in range(0, len(images), 2): # zwei Fotos je Zeile
appendix.append(IMAGES(images[i:i + 2], photos=True))
appendix.append(REF("Zurück zur Rack-Ansicht", rack_heading.anchor, prefix="↑ "))
appendix.append(REF(_("Back to rack elevation"), rack_heading.anchor, prefix="↑ "))
n = len(images)
return [REF(f"Anhang Rack-Fotos – Rack {rack.name}", heading.anchor, prefix=f"{n} Foto{'s' if n != 1 else ''}, siehe ")]
return [REF(
_("Appendix rack photos – rack %(name)s") % {"name": rack.name},
heading.anchor,
prefix=ngettext("%(n)d photo, see ", "%(n)d photos, see ", n) % {"n": n},
)]
@section("devices", "Geräte", "Infrastruktur", hint="Tabellen je Geräterolle")
@section("devices", gettext_lazy("Devices"), gettext_lazy("Infrastructure"), hint=gettext_lazy("Tables per device role"))
def devices(scope, opts):
blocks = [H(1, "Geräte")]
blocks = [H(1, _("Devices"))]
base = scope.devices().select_related(
"device_type__manufacturer", "role", "site", "location", "rack", "platform", "primary_ip4", "primary_ip6", "oob_ip", "tenant"
)
@@ -297,44 +303,44 @@ def devices(scope, opts):
blocks.append(H(2, role.name))
if opts.get("group_by_site"):
for site, site_devs in groupby(devs, key=lambda d: d.site):
blocks.append(H(3, f"Standort {site}"))
blocks.append(H(3, _("Site %(name)s") % {"name": site}))
blocks.append(_device_table(list(site_devs), columns, opts))
else:
blocks.append(_device_table(devs, columns, opts))
return blocks if found else _empty(opts, blocks)
@section("disks", "Datenträger & RAID", "Infrastruktur", default=False, hint="Aus Netbox-Utilities (falls installiert)")
@section("disks", gettext_lazy("Disks & RAID"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("From Netbox-Utilities (if installed)"))
def disks(scope, opts):
from . import disks_utilities
blocks = [H(1, "Datenträger & RAID")]
blocks = [H(1, _("Disks & RAID"))]
if not disks_utilities.is_installed():
return _empty(opts, blocks, "Keine Datenträger erfasst.")
return _empty(opts, blocks, _("No disks recorded."))
blocks += disks_utilities.disk_blocks(scope, opts)
return blocks if len(blocks) > 1 else _empty(opts, blocks)
@section("floorplans", "Raumpläne", "Infrastruktur", default=False, hint="Aus NetBox-FloorPlan (falls installiert)")
@section("floorplans", gettext_lazy("Floor plans"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("From NetBox-FloorPlan (if installed)"))
def floorplans(scope, opts):
from . import floorplan
blocks = [H(1, "Raumpläne")]
blocks = [H(1, _("Floor plans"))]
if not floorplan.is_installed():
return _empty(opts, blocks, "Keine Raumpläne erfasst.")
return _empty(opts, blocks, _("No floor plans recorded."))
blocks += floorplan.floorplan_blocks(scope, opts)
return blocks if len(blocks) > 1 else _empty(opts, blocks, "Keine Raumpläne erfasst.")
return blocks if len(blocks) > 1 else _empty(opts, blocks, _("No floor plans recorded."))
@section("power", "Stromversorgung", "Infrastruktur", default=False, hint="Power Panels & Feeds")
@section("power", gettext_lazy("Power"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Power panels & feeds"))
def power(scope, opts):
qs = scope.power_feeds().select_related("power_panel", "rack").order_by("power_panel__name", "name")
blocks = [H(1, "Stromversorgung")]
blocks = [H(1, _("Power"))]
if not qs.exists():
return _empty(opts, blocks)
blocks.append(
T(
["Panel", "Feed", "Rack", "Status", "Typ", "Phase", "Spannung", "Ampere"],
[_("Panel"), _("Feed"), _("Rack"), _("Status"), _("Type"), _("Phase"), _("Voltage"), _("Amperage")],
[[f.power_panel, f.name, f.rack, get(f, "status"), get(f, "type"), get(f, "phase"), f"{f.voltage} V", f"{f.amperage} A"] for f in qs],
)
)
@@ -370,10 +376,10 @@ def _vm_totals(vms):
)
@section("clusters", "Virtualisierungs-Cluster", "Infrastruktur", default=False, hint="Hosts und Ressourcen je Cluster")
@section("clusters", gettext_lazy("Virtualization clusters"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Hosts and resources per cluster"))
def clusters(scope, opts):
qs = scope.clusters().select_related("type", "group", "tenant").order_by("group__name", "name")
blocks = [H(1, "Virtualisierungs-Cluster")]
blocks = [H(1, _("Virtualization clusters"))]
if not qs.exists():
return _empty(opts, blocks)
vms_by_cluster = {}
@@ -395,22 +401,22 @@ def clusters(scope, opts):
_mb(disk),
])
details.append(H(2, f"Cluster {cluster.name}"))
details.append(H(2, _("Cluster %(name)s") % {"name": cluster.name}))
details.append(KV([
("Typ", cluster.type),
("Gruppe", cluster.group),
("Status", get(cluster, "status")),
("Zuordnung", getattr(cluster, "scope", None)),
("Mandant", cluster.tenant),
("Hosts", len(hosts)),
("VMs aktiv / gesamt", f"{active} / {len(vms)}"),
("Kerne / Threads (Hosts)", f"{p_cores} / {p_threads}" if p_cores else None),
("RAM (Hosts)", hardware_utilities.format_memory(p_ram) if p_ram else None),
("vCPU (Summe VMs)", num(vcpu) if vcpu else None),
("vCPU je Kern", f"{num(round(float(vcpu) / p_cores, 1))} : 1" if vcpu and p_cores else None),
("RAM (Summe VMs)", (_mb(ram) + ram_pct) if ram else None),
("Speicher (Summe)", _mb(disk) if disk else None),
("Beschreibung", cluster.description),
(_("Type"), cluster.type),
(_("Group"), cluster.group),
(_("Status"), get(cluster, "status")),
(_("Scope"), getattr(cluster, "scope", None)),
(_("Tenant"), cluster.tenant),
(_("Hosts"), len(hosts)),
(_("VMs active / total"), f"{active} / {len(vms)}"),
(_("Cores / threads (hosts)"), f"{p_cores} / {p_threads}" if p_cores else None),
(_("RAM (hosts)"), hardware_utilities.format_memory(p_ram) if p_ram else None),
(_("vCPU (total of VMs)"), num(vcpu) if vcpu else None),
(_("vCPU per core"), f"{num(round(float(vcpu) / p_cores, 1))} : 1" if vcpu and p_cores else None),
(_("RAM (total of VMs)"), (_mb(ram) + ram_pct) if ram else None),
(_("Storage (total)"), _mb(disk) if disk else None),
(_("Description"), cluster.description),
]))
if hosts:
rows = []
@@ -427,102 +433,102 @@ def clusters(scope, opts):
(f"{num(h_vcpu)} ({num(round(float(h_vcpu) / h_cores, 1))} : 1)" if h_cores else num(h_vcpu)) if h_vcpu else EMPTY,
(_mb(h_ram) + (f" ({round(h_ram / (h_pram * 1024) * 100)} %)" if h_pram else "")) if h_ram else EMPTY,
])
details.append(T(["Host", "Hersteller / Modell", "CPU", "RAM", "VMs", "vCPU", "RAM VMs"], rows))
details.append(T([_("Host"), _("Manufacturer / model"), _("CPU"), _("RAM"), _("VMs"), _("vCPU"), _("RAM of VMs")], rows))
if any(vm.device_id is None for vm in vms):
details.append(P("VMs ohne festen Host sind nur in den Cluster-Summen enthalten."))
details.append(P(_("VMs without a fixed host are only included in the cluster totals.")))
blocks.append(T(["Cluster", "Typ", "Hosts", "VMs aktiv / gesamt", "vCPU / Kerne", "RAM VMs / Hosts", "Speicher"], summary))
blocks.append(T([_("Cluster"), _("Type"), _("Hosts"), _("VMs active / total"), _("vCPU / cores"), _("RAM of VMs / hosts"), _("Storage")], summary))
return blocks + details
@section("vms", "Virtuelle Maschinen", "Infrastruktur", default=False, hint="Cluster, Ressourcen, IP")
@section("vms", gettext_lazy("Virtual machines"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Cluster, resources, IP"))
def vms(scope, opts):
qs = scope.virtual_machines().select_related("cluster", "role", "platform", "primary_ip4", "primary_ip6").order_by("cluster__name", "name")
blocks = [H(1, "Virtuelle Maschinen")]
blocks = [H(1, _("Virtual machines"))]
if not qs.exists():
return _empty(opts, blocks)
blocks.append(
T(
["Name", "Cluster", "Rolle", "Status", "OS", "vCPU", "RAM (MB)", "Disk (MB)", "IP"],
[_("Name"), _("Cluster"), _("Role"), _("Status"), _("OS"), "vCPU", _("RAM (MB)"), _("Disk (MB)"), "IP"],
[[vm.name, vm.cluster, vm.role, get(vm, "status"), vm.platform, vm.vcpus, vm.memory, vm.disk, primary_ips(vm, opts)] for vm in qs],
)
)
return blocks
@section("vrfs", "VRFs", "Netzwerk", hint="Inkl. Route Targets")
@section("vrfs", gettext_lazy("VRFs"), gettext_lazy("Network"), hint=gettext_lazy("Including route targets"))
def vrfs(scope, opts):
qs = scope.vrfs().select_related("tenant").prefetch_related("import_targets", "export_targets").order_by("name")
blocks = [H(1, "VRFs")]
blocks = [H(1, _("VRFs"))]
if not qs.exists():
return _empty(opts, blocks)
blocks.append(
T(
["Name", "RD", "Mandant", "Import-RT", "Export-RT", "Beschreibung"],
[_("Name"), "RD", _("Tenant"), _("Import RT"), _("Export RT"), _("Description")],
[[v.name, v.rd, v.tenant, v.import_targets, v.export_targets, v.description] for v in qs],
)
)
return blocks
@section("prefixes", "IP-Netze", "Netzwerk", hint="Präfixe gruppiert nach VRF")
@section("prefixes", gettext_lazy("IP networks"), gettext_lazy("Network"), hint=gettext_lazy("Prefixes grouped by VRF"))
def prefixes(scope, opts):
qs = scope.prefixes().select_related("vrf", "vlan", "role", "tenant").order_by("vrf__name", "prefix")
qs = qs.filter(prefix__family__in=ip_versions(opts))
blocks = [H(1, "IP-Netze")]
blocks = [H(1, _("IP networks"))]
if not qs.exists():
return _empty(opts, blocks)
for vrf, items in groupby(qs, key=lambda p: p.vrf):
blocks.append(H(2, f"VRF {vrf}" if vrf else "Global"))
blocks.append(H(2, f"VRF {vrf}" if vrf else _("Global")))
blocks.append(
T(
["Präfix", "VLAN", "Rolle", "Status", "Scope", "Beschreibung"],
[_("Prefix"), "VLAN", _("Role"), _("Status"), _("Scope"), _("Description")],
[[p.prefix, p.vlan, p.role, get(p, "status"), p.scope, p.description] for p in items],
)
)
return blocks
@section("vlans", "VLANs", "Netzwerk", hint="VID, Name, Gruppe, Rolle")
@section("vlans", gettext_lazy("VLANs"), gettext_lazy("Network"), hint=gettext_lazy("VID, name, group, role"))
def vlans(scope, opts):
qs = scope.vlans().select_related("group", "site", "role", "tenant").order_by("group__name", "vid")
blocks = [H(1, "VLANs")]
blocks = [H(1, _("VLANs"))]
if not qs.exists():
return _empty(opts, blocks)
blocks.append(
T(
["VID", "Name", "Gruppe", "Standort", "Rolle", "Status", "Beschreibung"],
["VID", _("Name"), _("Group"), _("Site"), _("Role"), _("Status"), _("Description")],
[[v.vid, v.name, v.group, v.site, v.role, get(v, "status"), v.description] for v in qs],
)
)
return blocks
@section("ips", "IP-Adressen", "Netzwerk", default=False, hint="Ausführlich – kann lang werden")
@section("ips", gettext_lazy("IP addresses"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Detailed – can get long"))
def ips(scope, opts):
qs = scope.ip_addresses().select_related("vrf", "tenant").prefetch_related("assigned_object").order_by("vrf__name", "address")
qs = qs.filter(address__family__in=ip_versions(opts))
blocks = [H(1, "IP-Adressen")]
blocks = [H(1, _("IP addresses"))]
if not qs.exists():
return _empty(opts, blocks)
for vrf, items in groupby(qs, key=lambda i: i.vrf):
blocks.append(H(2, f"VRF {vrf}" if vrf else "Global"))
blocks.append(H(2, f"VRF {vrf}" if vrf else _("Global")))
rows = []
for ip in items:
obj = ip.assigned_object
parent = getattr(obj, "parent_object", None)
rows.append([ip.address, get(ip, "status"), get(ip, "role"), ip.dns_name, f"{parent} – {obj}" if parent else obj, ip.description])
blocks.append(T(["Adresse", "Status", "Rolle", "DNS-Name", "Zugewiesen an", "Beschreibung"], rows))
blocks.append(T([_("Address"), _("Status"), _("Role"), _("DNS name"), _("Assigned to"), _("Description")], rows))
return blocks
@section("wireless", "WLANs", "Netzwerk", default=False, hint="SSIDs, Authentifizierung")
@section("wireless", gettext_lazy("Wireless LANs"), gettext_lazy("Network"), default=False, hint=gettext_lazy("SSIDs, authentication"))
def wireless(scope, opts):
qs = scope.wireless_lans().select_related("group", "vlan").order_by("ssid")
blocks = [H(1, "WLANs")]
blocks = [H(1, _("Wireless LANs"))]
if not qs.exists():
return _empty(opts, blocks)
headers = ["SSID", "Gruppe", "VLAN", "Status", "Authentifizierung", "Verschlüsselung"]
headers = ["SSID", _("Group"), "VLAN", _("Status"), _("Authentication"), _("Cipher")]
show_psk = opts.get("include_secrets")
if show_psk:
headers.append("PSK")
@@ -536,15 +542,15 @@ def wireless(scope, opts):
return blocks
@section("circuits", "Leitungen", "Netzwerk", default=False, hint="Provider, Leitungs-ID, Bandbreite")
@section("circuits", gettext_lazy("Circuits"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Provider, circuit ID, bandwidth"))
def circuits(scope, opts):
qs = scope.circuits().select_related("provider", "type", "tenant").order_by("provider__name", "cid")
blocks = [H(1, "Leitungen")]
blocks = [H(1, _("Circuits"))]
if not qs.exists():
return _empty(opts, blocks)
blocks.append(
T(
["Leitungs-ID", "Provider", "Typ", "Status", "Bandbreite (Kbit/s)", "Beschreibung"],
[_("Circuit ID"), _("Provider"), _("Type"), _("Status"), _("Commit rate (Kbps)"), _("Description")],
[[c.cid, c.provider, c.type, get(c, "status"), c.commit_rate, c.description] for c in qs],
)
)
@@ -558,23 +564,23 @@ DEFAULT_LICENSE_SOURCES = [
"model": "netbox_lifecycle.licenseassignment",
"device_field": "device",
"columns": [
("Lizenz", "license"),
("Hersteller", "license.manufacturer"),
("Gerät", "device"),
("Anzahl", "quantity"),
("Vertrag", "license.contract"),
("Beschreibung", "description"),
(gettext_lazy("License"), "license"),
(gettext_lazy("Manufacturer"), "license.manufacturer"),
(gettext_lazy("Device"), "device"),
(gettext_lazy("Quantity"), "quantity"),
(gettext_lazy("Contract"), "license.contract"),
(gettext_lazy("Description"), "description"),
],
},
]
@section("licenses", "Lizenzen", "Verträge & Lizenzen", hint="Aus NetBox-SLM oder anderem Lizenz-Plugin")
@section("licenses", gettext_lazy("Licenses"), gettext_lazy("Contracts & licenses"), hint=gettext_lazy("From NetBox-SLM or another license plugin"))
def licenses(scope, opts):
from . import licenses_slm
sources = get_plugin_config("netbox_customer_export", "license_sources") or DEFAULT_LICENSE_SOURCES
blocks = [H(1, "Lizenzen")]
blocks = [H(1, _("Licenses"))]
found_source = False
if licenses_slm.is_installed():
found_source = True
@@ -595,15 +601,15 @@ def licenses(scope, opts):
cols = src["columns"]
blocks.append(T([c[0] for c in cols], [[get(o, c[1]) for c in cols] for o in qs]))
if not found_source:
return _empty(opts, blocks, "Kein Lizenz-Plugin installiert (NetBox-SLM oder netbox-lifecycle) – siehe README.")
return _empty(opts, blocks, _("No license plugin installed (NetBox-SLM or netbox-lifecycle) – see README."))
return blocks if len(blocks) > 1 else _empty(opts, blocks)
@section("topology", "Netzwerk-Topologie", "Netzwerk", default=False, hint="Diagramm mit Symbolen, wie Packet Tracer")
@section("topology", gettext_lazy("Network topology"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Diagram with symbols, like Packet Tracer"))
def topology(scope, opts):
from .topology import build_graphs, build_location_graphs, render_png
title = H(1, "Netzwerk-Topologie")
title = H(1, _("Network topology"))
scopes = opts.get("topo_scope") or ["site"]
ports = "ports" in (opts.get("topo_details") or [])
pages = [] # (Überschriften, Graph) – je eine Querformat-Seite
@@ -611,13 +617,15 @@ def topology(scope, opts):
pages += [([H(2, g.title)], g) for g in build_graphs(scope, opts, per="site")]
if "locations" in scopes:
locs = build_location_graphs(scope, opts)
pages += [(([H(2, "Lokationsübersicht")] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(locs)]
pages += [(([H(2, _("Location overview"))] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(locs)]
if "locations_all" in scopes:
pages += [([H(2, _("Cross-site location overview"))], g) for g in build_location_graphs(scope, opts, combined=True)]
if "rack" in scopes:
racks = build_graphs(scope, opts, per="rack")
# Rack-Seiten unter einer gemeinsamen Zwischenüberschrift, Racks selbst eine Ebene tiefer (kürzeres Inhaltsverzeichnis)
pages += [(([H(2, "Topologie je Rack")] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(racks)]
pages += [(([H(2, _("Topology per rack"))] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(racks)]
if not pages:
return _empty(opts, [title], "Keine verkabelten Geräte gefunden.")
return _empty(opts, [title], _("No cabled devices found."))
# Die Abschnittsüberschrift steht mit auf der ersten Seite
return [
LANDSCAPE(([title] if i == 0 else []) + headings, render_png(g, show_ports=ports))
+3 -2
View File
@@ -4,6 +4,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMix
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views import View
from .forms import TopologySymbolForm
@@ -75,7 +76,7 @@ class SymbolEditView(PermissionRequiredMixin, View):
form = TopologySymbolForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
obj = form.save()
messages.success(request, f"Topologie-Symbol für „{obj}“ gespeichert.")
messages.success(request, _("Topology symbol for “%(name)s” saved.") % {"name": obj})
return redirect(f"plugins:{APP}:symbol_list")
return self._render(request, obj, form)
@@ -92,5 +93,5 @@ class SymbolDeleteView(PermissionRequiredMixin, View):
if obj.icon:
obj.icon.delete(save=False)
obj.delete()
messages.success(request, f"Topologie-Symbol für „{name}“ gelöscht – es gilt wieder die automatische Erkennung.")
messages.success(request, _("Topology symbol for “%(name)s” deleted – automatic detection applies again.") % {"name": name})
return redirect(f"plugins:{APP}:symbol_list")
+26 -24
View File
@@ -4,36 +4,38 @@ from collections import OrderedDict
from functools import lru_cache
from io import BytesIO
from django.utils.translation import gettext_lazy as _
# Schlüssel -> (Bezeichnung, Ebene im Diagramm; kleiner = weiter oben)
KINDS = OrderedDict(
[
("cloud", ("Internet / Provider", 0)),
("location", ("Lokation / Verteiler", 3)),
("modem", ("Modem / NTU / Medienkonverter", 1)),
("firewall", ("Firewall", 1)),
("router", ("Router", 1)),
("l3switch", ("Layer-3-Switch / Core", 2)),
("switch", ("Switch", 3)),
("radio", ("Funkstrecke / Richtfunk", 3)),
("patchpanel", ("Patchfeld / Rangierverteiler", 3)),
("wlc", ("WLAN-Controller", 3)),
("poe", ("PoE-Injektor", 4)),
("ap", ("Access Point", 4)),
("server", ("Server", 4)),
("storage", ("Storage / SAN (MSA)", 4)),
("nas", ("NAS", 4)),
("tape", ("Bandlaufwerk / Tape Library", 4)),
("ups", ("USV / ATS", 4)),
("pbx", ("Telefonanlage", 4)),
("phone", ("IP-Telefon", 4)),
("pc", ("PC / Client", 4)),
("printer", ("Drucker", 4)),
("camera", ("Kamera", 4)),
("generic", ("Sonstiges Gerät", 4)),
("cloud", (_("Internet / provider"), 0)),
("location", (_("Location / distribution"), 3)),
("modem", (_("Modem / NTU / media converter"), 1)),
("firewall", (_("Firewall"), 1)),
("router", (_("Router"), 1)),
("l3switch", (_("Layer 3 switch / core"), 2)),
("switch", (_("Switch"), 3)),
("radio", (_("Radio link / microwave"), 3)),
("patchpanel", (_("Patch panel / distribution frame"), 3)),
("wlc", (_("Wireless controller"), 3)),
("poe", (_("PoE injector"), 4)),
("ap", (_("Access point"), 4)),
("server", (_("Server"), 4)),
("storage", (_("Storage / SAN (MSA)"), 4)),
("nas", (_("NAS"), 4)),
("tape", (_("Tape drive / tape library"), 4)),
("ups", (_("UPS / ATS"), 4)),
("pbx", (_("Phone system (PBX)"), 4)),
("phone", (_("IP phone"), 4)),
("pc", (_("PC / client"), 4)),
("printer", (_("Printer"), 4)),
("camera", (_("Camera"), 4)),
("generic", (_("Other device"), 4)),
]
)
HIDDEN = "hidden"
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k not in ("cloud", "location")] + [(HIDDEN, "In Topologie ausblenden")]
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k not in ("cloud", "location")] + [(HIDDEN, _("Hide in topology"))]
# Reihenfolge wichtig: erster Treffer gewinnt. None = passiv, nicht zeichnen.
# Tippvarianten („Acces Point“, „Controler“, „Libary“) sind absichtlich mit abgedeckt.
+4 -2
View File
@@ -1,5 +1,6 @@
from django.urls import reverse
from django.utils.html import format_html
from django.utils.translation import gettext as _
from netbox.plugins import PluginTemplateExtension
@@ -13,8 +14,9 @@ class CustomerExportButton(PluginTemplateExtension):
kwargs={"kind": obj._meta.model_name, "pk": obj.pk},
)
return format_html(
'<a href="{}" class="btn btn-primary"><i class="mdi mdi-file-document-outline"></i> Kundendoku</a>',
'<a href="{}" class="btn btn-primary"><i class="mdi mdi-file-document-outline"></i> {}</a>',
url,
_("Customer Docs"),
)
@@ -37,7 +39,7 @@ class TopologySymbolButton(PluginTemplateExtension):
else:
url = f"{reverse('plugins:netbox_customer_export:symbol_add')}?{field}={obj.pk}"
return format_html(
'<a href="{}" class="btn btn-outline-primary"><i class="mdi mdi-shape-outline"></i> Topologie-Symbol</a>', url
'<a href="{}" class="btn btn-outline-primary"><i class="mdi mdi-shape-outline"></i> {}</a>', url, _("Topology Symbol")
)
@@ -1,6 +1,6 @@
<div class="ce-pills">
{% load i18n %}<div class="ce-pills">
{% for cb in field %}
<input type="checkbox" class="btn-check" name="{{ cb.data.name }}" value="{{ cb.data.value }}" id="{{ cb.id_for_label }}" autocomplete="off"{% if cb.data.selected %} checked{% endif %}>
<label class="btn btn-sm btn-outline-primary" for="{{ cb.id_for_label }}">{{ cb.choice_label }}</label>
{% empty %}<span class="text-muted small">Keine Einträge im Scope.</span>{% endfor %}
{% empty %}<span class="text-muted small">{% trans "No entries in scope." %}</span>{% endfor %}
</div>
@@ -1,6 +1,6 @@
<div class="table-responsive">
{% load i18n %}<div class="table-responsive">
<table class="table table-hover card-table align-middle">
<thead><tr><th style="width:56px"></th><th>Zuordnung</th><th>Symbol</th><th></th></tr></thead>
<thead><tr><th style="width:56px"></th><th>{% trans "Assignment" %}</th><th>{% trans "Symbol" %}</th><th></th></tr></thead>
<tbody>
{% for s, preview in rows %}
<tr>
@@ -9,13 +9,13 @@
{% if s.device_type %}<a href="{{ s.device_type.get_absolute_url }}">{{ s.device_type.manufacturer }} {{ s.device_type.model }}</a>
{% else %}<a href="{{ s.role.get_absolute_url }}">{{ s.role }}</a>{% endif %}
</td>
<td>{% if s.icon %}<span class="badge text-bg-blue">Eigenes Icon</span>{% endif %} {{ s.get_kind_display }}</td>
<td>{% if s.icon %}<span class="badge text-bg-blue">{% trans "Custom icon" %}</span>{% endif %} {{ s.get_kind_display }}</td>
<td class="text-end text-nowrap">
{% if perms.netbox_customer_export.change_topologysymbol %}
<a href="{{ s.get_absolute_url }}" class="btn btn-sm btn-warning" title="Bearbeiten"><i class="mdi mdi-pencil"></i></a>
<a href="{{ s.get_absolute_url }}" class="btn btn-sm btn-warning" title="{% trans "Edit" %}"><i class="mdi mdi-pencil"></i></a>
{% endif %}
{% if perms.netbox_customer_export.delete_topologysymbol %}
<a href="{% url 'plugins:netbox_customer_export:symbol_delete' pk=s.pk %}" class="btn btn-sm btn-danger" title="Löschen"><i class="mdi mdi-trash-can-outline"></i></a>
<a href="{% url 'plugins:netbox_customer_export:symbol_delete' pk=s.pk %}" class="btn btn-sm btn-danger" title="{% trans "Delete" %}"><i class="mdi mdi-trash-can-outline"></i></a>
{% endif %}
</td>
</tr>
@@ -1,16 +1,17 @@
{% extends 'generic/_base.html' %}
{% block title %}{{ object }} löschen{% endblock %}
{% load i18n %}
{% block title %}{% blocktrans %}Delete {{ object }}{% endblocktrans %}{% endblock %}
{% block content %}
<form method="post" class="mt-3">
{% csrf_token %}
<div class="card border-danger">
<div class="card-body">
<p>Soll das Branding-Profil <strong>{{ object }}</strong> wirklich gelöscht werden?
Logo und Word-Vorlage des Profils werden ebenfalls entfernt.</p>
<p>{% blocktrans trimmed %}Do you really want to delete the branding profile <strong>{{ object }}</strong>?
The profile's logo and Word template will be removed as well.{% endblocktrans %}</p>
</div>
<div class="card-footer text-end">
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> Löschen</button>
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> {% trans "Delete" %}</button>
</div>
</div>
</form>
@@ -1,5 +1,6 @@
{% extends 'generic/_base.html' %}
{% block title %}{% if object.pk %}{{ object }} bearbeiten{% else %}Neues Branding-Profil{% endif %}{% endblock %}
{% load i18n %}
{% block title %}{% if object.pk %}{% blocktrans %}Edit {{ object }}{% endblocktrans %}{% else %}{% trans "New branding profile" %}{% endif %}{% endblock %}
{% block content %}
<style>
.ce-colors { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: .75rem; }
@@ -14,7 +15,7 @@
<div class="row g-3">
<div class="col-lg-6">
<div class="card h-100">
<h2 class="card-header"><i class="mdi mdi-domain"></i> Allgemein</h2>
<h2 class="card-header"><i class="mdi mdi-domain"></i> {% trans "General" %}</h2>
<div class="card-body">
{% include 'netbox_customer_export/_field.html' with field=form.name %}
<div class="mb-3 d-flex gap-2 align-items-center">{{ form.is_default }} <label for="{{ form.is_default.id_for_label }}" class="m-0">{{ form.is_default.label }}</label>
@@ -23,7 +24,7 @@
{% include 'netbox_customer_export/_field.html' with field=form.footer_text %}
<div class="mb-3">
<label class="form-label" for="{{ form.logo.id_for_label }}">{{ form.logo.label }}</label>
{% if object.logo %}<div class="mb-2"><img src="{{ object.logo.url }}" class="ce-logo-preview" alt="Aktuelles Logo"></div>{% endif %}
{% if object.logo %}<div class="mb-2"><img src="{{ object.logo.url }}" class="ce-logo-preview" alt="{% trans "Current logo" %}"></div>{% endif %}
{{ form.logo }}
<div class="form-text">{{ form.logo.help_text }}</div>
{% for e in form.logo.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
@@ -34,7 +35,7 @@
<div class="col-lg-6">
<div class="card h-100">
<h2 class="card-header"><i class="mdi mdi-palette"></i> Farben & Schrift</h2>
<h2 class="card-header"><i class="mdi mdi-palette"></i> {% trans "Colours & font" %}</h2>
<div class="card-body">
<div class="ce-colors mb-3">
{% for field in form %}{% if field.name in 'primary_color accent_color header_text_color label_bg_color stripe_color' %}
@@ -73,9 +74,9 @@
</div>
<div class="d-flex justify-content-end gap-2 mt-3">
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
{% if object.pk %}<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=object.pk %}" target="_blank" class="btn btn-outline-primary"><i class="mdi mdi-eye"></i> Vorschau</a>{% endif %}
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> Speichern</button>
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
{% if object.pk %}<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=object.pk %}" target="_blank" class="btn btn-outline-primary"><i class="mdi mdi-eye"></i> {% trans "Preview" %}</a>{% endif %}
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> {% trans "Save" %}</button>
</div>
</form>
{% endblock %}
@@ -1,9 +1,10 @@
{% extends 'generic/_base.html' %}
{% block title %}Branding-Profile{% endblock %}
{% load i18n %}
{% block title %}{% trans "Branding Profiles" %}{% endblock %}
{% block controls %}
{% if perms.netbox_customer_export.add_brandingprofile %}
<div class="btn-list">
<a href="{% url 'plugins:netbox_customer_export:branding_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> Hinzufügen</a>
<a href="{% url 'plugins:netbox_customer_export:branding_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> {% trans "Add" %}</a>
</div>
{% endif %}
{% endblock %}
@@ -16,38 +17,38 @@
<div class="table-responsive">
<table class="table table-hover card-table">
<thead>
<tr><th>Name</th><th>Logo</th><th>Firma</th><th>Farben</th><th>Schrift</th><th>Word-Vorlage</th><th></th></tr>
<tr><th>{% trans "Name" %}</th><th>{% trans "Logo" %}</th><th>{% trans "Company" %}</th><th>{% trans "Colours" %}</th><th>{% trans "Font" %}</th><th>{% trans "Word template" %}</th><th></th></tr>
</thead>
<tbody>
{% for p in profiles %}
<tr>
<td>
{% if perms.netbox_customer_export.change_brandingprofile %}<a href="{{ p.get_absolute_url }}">{{ p.name }}</a>{% else %}{{ p.name }}{% endif %}
{% if p.is_default %}<span class="badge text-bg-green ms-1">Standard</span>{% endif %}
{% if p.is_default %}<span class="badge text-bg-green ms-1">{% trans "Default" %}</span>{% endif %}
</td>
<td>{% if p.logo %}<img src="{{ p.logo.url }}" class="ce-logo" alt="">{% else %}<span class="text-muted">—</span>{% endif %}</td>
<td>{{ p.company_name|default:"—" }}</td>
<td>
<span class="ce-swatch" style="background:#{{ p.primary_color }}" title="Primär #{{ p.primary_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.accent_color }}" title="Akzent #{{ p.accent_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.label_bg_color }}" title="Beschriftungen #{{ p.label_bg_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.stripe_color }}" title="Zebrastreifen #{{ p.stripe_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.primary_color }}" title="{% trans "Primary" %} #{{ p.primary_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.accent_color }}" title="{% trans "Accent" %} #{{ p.accent_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.label_bg_color }}" title="{% trans "Labels" %} #{{ p.label_bg_color }}"></span>
<span class="ce-swatch" style="background:#{{ p.stripe_color }}" title="{% trans "Row stripes" %} #{{ p.stripe_color }}"></span>
</td>
<td>{{ p.font_family }}, {{ p.font_size }} pt</td>
<td>{% if p.docx_template %}<i class="mdi mdi-file-word-box text-primary"></i> {{ p.docx_template.name|cut:"customer-export/templates/" }}{% else %}<span class="text-muted">—</span>{% endif %}</td>
<td class="text-end text-nowrap">
<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=p.pk %}" target="_blank" class="btn btn-sm btn-outline-secondary" title="Vorschau"><i class="mdi mdi-eye"></i></a>
<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=p.pk %}" target="_blank" class="btn btn-sm btn-outline-secondary" title="{% trans "Preview" %}"><i class="mdi mdi-eye"></i></a>
{% if perms.netbox_customer_export.change_brandingprofile %}
<a href="{{ p.get_absolute_url }}" class="btn btn-sm btn-warning" title="Bearbeiten"><i class="mdi mdi-pencil"></i></a>
<a href="{{ p.get_absolute_url }}" class="btn btn-sm btn-warning" title="{% trans "Edit" %}"><i class="mdi mdi-pencil"></i></a>
{% endif %}
{% if perms.netbox_customer_export.delete_brandingprofile %}
<a href="{% url 'plugins:netbox_customer_export:branding_delete' pk=p.pk %}" class="btn btn-sm btn-danger" title="Löschen"><i class="mdi mdi-trash-can-outline"></i></a>
<a href="{% url 'plugins:netbox_customer_export:branding_delete' pk=p.pk %}" class="btn btn-sm btn-danger" title="{% trans "Delete" %}"><i class="mdi mdi-trash-can-outline"></i></a>
{% endif %}
</td>
</tr>
{% empty %}
<tr><td colspan="7" class="text-center text-muted py-4">
Noch keine Branding-Profile angelegt. Bis dahin gelten die Einstellungen aus <code>configuration.py</code>.
{% blocktrans trimmed %}No branding profiles yet. Until then, the settings from <code>configuration.py</code> apply.{% endblocktrans %}
</td></tr>
{% endfor %}
</tbody>
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="de">
{% load i18n %}<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8">
<title>{{ doc.title }}</title>
@@ -7,8 +7,8 @@
:root { --primary: #{{ b.primary_color }}; --accent: #{{ b.accent_color }}; --head-text: #{{ b.header_text_color }}; --label-bg: #{{ b.label_bg_color }}; --stripe: #{{ b.stripe_color }}; }
@page { size: A4; margin: 20mm 15mm 20mm 15mm;
@bottom-left { content: element(footer); }
@bottom-right { content: "Seite " counter(page) " / " counter(pages); font-size: 7pt; color: #777; } }
/* Querformat: schmale Ränder, damit die Topologie möglichst groß wird */
@bottom-right { content: "{% filter escapejs %}{% trans "Page" %}{% endfilter %} " counter(page) " / " counter(pages); font-size: 7pt; color: #777; } }
/* Landscape: narrow margins so the topology gets as large as possible */
@page landscape { size: A4 landscape; margin: 7mm 7mm 11mm 7mm; }
@page cover { @bottom-left { content: none } @bottom-right { content: none } }
body { font-family: "{{ b.font_family }}", "Segoe UI", "DejaVu Sans", Arial, sans-serif; font-size: {{ b.font_size }}pt; color: #222; }
@@ -66,13 +66,13 @@
<h1>{{ doc.title }}</h1>
{% if doc.subtitle %}<div class="subtitle">{{ doc.subtitle }}</div>{% endif %}
<div class="meta">
Stand: {{ doc.meta.date }}<br>
Erstellt von: {{ doc.meta.author }}<br>
{% trans "As of" %}: {{ doc.meta.date }}<br>
{% trans "Created by" %}: {{ doc.meta.author }}<br>
{{ b.company_name }}
</div>
</section>
<nav class="toc">
<h2>Inhaltsverzeichnis</h2>
<h2>{% trans "Table of contents" %}</h2>
{% for h in doc.toc %}<div class="l{{ h.level }}"><a href="#{{ h.anchor }}">{{ h.text }}</a></div>{% endfor %}
</nav>
{% for b in doc.blocks %}
@@ -1,6 +1,7 @@
{% extends 'generic/_base.html' %}
{% load i18n %}
{% load form_helpers %}
{% block title %}Kundendokumentation: {{ object }}{% endblock %}
{% block title %}{% blocktrans %}Customer documentation: {{ object }}{% endblocktrans %}{% endblock %}
{% block subtitle %}
<div class="text-muted"><span class="badge text-bg-secondary">{{ scope.label }}</span> <a href="{{ object.get_absolute_url }}">{{ object }}</a></div>
{% endblock %}
@@ -42,9 +43,9 @@
{# --- links: Dokument --- #}
<div class="col-xl-4">
<div class="card">
<h2 class="card-header"><i class="mdi mdi-file-document-outline"></i> Dokument</h2>
<h2 class="card-header"><i class="mdi mdi-file-document-outline"></i> {% trans "Document" %}</h2>
<div class="card-body">
<div class="ce-label mt-0">Format</div>
<div class="ce-label mt-0">{% trans "Format" %}</div>
<div class="btn-group w-100 ce-format mb-3" role="group">
{% for value, label in form.format.field.choices %}
<input type="radio" class="btn-check" name="format" id="fmt-{{ value }}" value="{{ value }}" autocomplete="off"{% if form.format.value == value %} checked{% endif %}>
@@ -54,20 +55,20 @@
</label>
{% endfor %}
</div>
<div class="mb-3"><label class="form-label" for="{{ form.title.id_for_label }}">Titel</label>{{ form.title }}</div>
<div class="mb-3"><label class="form-label" for="{{ form.subtitle.id_for_label }}">Untertitel</label>{{ form.subtitle }}</div>
<div class="mb-3"><label class="form-label" for="{{ form.author.id_for_label }}">Erstellt von</label>{{ form.author }}<div class="form-text">Leer = dein Benutzername</div></div>
<div class="mb-3"><label class="form-label" for="{{ form.title.id_for_label }}">{{ form.title.label }}</label>{{ form.title }}</div>
<div class="mb-3"><label class="form-label" for="{{ form.subtitle.id_for_label }}">{{ form.subtitle.label }}</label>{{ form.subtitle }}</div>
<div class="mb-3"><label class="form-label" for="{{ form.author.id_for_label }}">{{ form.author.label }}</label>{{ form.author }}<div class="form-text">{% trans "Empty = your user name" %}</div></div>
{% if form.branding.field.choices|length > 1 %}
<div class="mb-3"><label class="form-label" for="{{ form.branding.id_for_label }}">Design / Firma</label>{{ form.branding }}</div>
<div class="mb-3"><label class="form-label" for="{{ form.branding.id_for_label }}">{{ form.branding.label }}</label>{{ form.branding }}</div>
{% else %}
<input type="hidden" name="branding" value="{{ form.branding.field.choices.0.0 }}">
{% endif %}
<div class="ce-label">IP-Versionen</div>
<div class="ce-label">{{ form.ip_versions.label }}</div>
{% include 'netbox_customer_export/_pills.html' with field=form.ip_versions %}
<div class="form-text mb-2">Gilt für Management-/OOB-IPs, VMs, Topologie, IP-Netze und IP-Adressen.</div>
<div class="form-text mb-2">{% trans "Applies to management/OOB IPs, VMs, topology, IP networks and IP addresses." %}</div>
<div class="ce-label">Optionen</div>
<div class="ce-label">{% trans "Options" %}</div>
<label class="ce-switch">{{ form.include_empty }} {{ form.include_empty.label }}</label>
{% if form.include_secrets %}
<label class="ce-switch text-danger">{{ form.include_secrets }} {{ form.include_secrets.label }}</label>
@@ -79,13 +80,13 @@
{# --- rechts: Inhalte + Detailoptionen --- #}
<div class="col-xl-8">
<div class="card">
<h2 class="card-header"><i class="mdi mdi-format-list-checks"></i> Inhalte</h2>
<h2 class="card-header"><i class="mdi mdi-format-list-checks"></i> {% trans "Contents" %}</h2>
<div class="card-body">
{% for group, sections in section_groups.items %}
<div class="ce-group" data-ce-group>
<div class="ce-group-head">
<h5>{{ group }}</h5>
<span><a data-ce-all>Alle</a> · <a data-ce-none>Keine</a></span>
<span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span>
</div>
<div class="ce-tiles">
{% for cb in form.sections %}{% for s in sections %}{% if s.key == cb.data.value %}
@@ -103,13 +104,13 @@
<div class="row g-3 mt-0">
<div class="col-lg-7">
<div class="card ce-card h-100" data-ce-depends="devices">
<h2 class="card-header"><i class="mdi mdi-server-network"></i> Geräte</h2>
<h2 class="card-header"><i class="mdi mdi-server-network"></i> {% trans "Devices" %}</h2>
<div class="card-body">
<div data-ce-group>
<div class="ce-group-head"><h5>Geräterollen</h5><span><a data-ce-all>Alle</a> · <a data-ce-none>Keine</a></span></div>
<div class="ce-group-head"><h5>{{ form.roles.label }}</h5><span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span></div>
{% include 'netbox_customer_export/_pills.html' with field=form.roles %}
</div>
<div class="ce-label">Spalten</div>
<div class="ce-label">{% trans "Columns" %}</div>
{% include 'netbox_customer_export/_pills.html' with field=form.device_columns %}
<label class="ce-switch mt-3">{{ form.group_by_site }} {{ form.group_by_site.label }}</label>
</div>
@@ -117,13 +118,13 @@
</div>
<div class="col-lg-5">
<div class="card ce-card h-100" data-ce-depends="racks">
<h2 class="card-header"><i class="mdi mdi-server"></i> Racks</h2>
<h2 class="card-header"><i class="mdi mdi-server"></i> {% trans "Racks" %}</h2>
<div class="card-body">
<label class="ce-switch">{{ form.rack_svg }} Rack-Ansichten einbetten</label>
<label class="ce-switch">{{ form.rack_svg }} {% trans "Embed rack elevations" %}</label>
<label class="ce-switch">{{ form.rack_images }} {{ form.rack_images.label }}</label>
<div class="ce-label">Seiten</div>
<div class="ce-label">{% trans "Faces" %}</div>
{% include 'netbox_customer_export/_pills.html' with field=form.rack_faces %}
<div class="ce-label">Weiteres</div>
<div class="ce-label">{% trans "More" %}</div>
<label class="ce-switch">{{ form.rack_devices }} {{ form.rack_devices.label }}</label>
<label class="ce-switch">{{ form.rack_pagebreak }} {{ form.rack_pagebreak.label }}</label>
</div>
@@ -131,7 +132,7 @@
</div>
<div class="col-lg-5">
<div class="card ce-card h-100" data-ce-depends="disks">
<h2 class="card-header"><i class="mdi mdi-harddisk"></i> Datenträger</h2>
<h2 class="card-header"><i class="mdi mdi-harddisk"></i> {% trans "Disks" %}</h2>
<div class="card-body">
<label class="ce-switch">{{ form.disk_install_date }} {{ form.disk_install_date.label }}</label>
</div>
@@ -139,17 +140,17 @@
</div>
</div>
<div class="card ce-card mt-3" data-ce-depends="racks">
<h2 class="card-header"><i class="mdi mdi-image-multiple-outline"></i> Rack-Fotos</h2>
<h2 class="card-header"><i class="mdi mdi-image-multiple-outline"></i> {% trans "Rack photos" %}</h2>
<div class="card-body">
{% if not rack_photos %}
<div class="text-secondary">Keine Bildanhänge an Racks in diesem Scope gefunden. Fotos lassen sich am Rack über <em>Bild anhängen</em> hochladen.</div>
<div class="text-secondary">{% trans "No image attachments found on racks in this scope. Photos can be uploaded on the rack via <em>Attach an image</em>." %}</div>
{% else %}
<div class="form-text mt-0 mb-3">Ausgewählte Fotos erscheinen im Anhang am Dokumentende, unter der jeweiligen Rack-Ansicht steht ein Verweis darauf.</div>
<div class="form-text mt-0 mb-3">{% trans "Selected photos appear in the appendix at the end of the document; a link to them is placed below the rack elevation." %}</div>
{% for rack, atts in rack_photos %}
<div class="ce-photo-rack" data-ce-group>
<div class="ce-group-head">
<h5>{{ rack.name }} <span class="fw-normal" style="text-transform: none">· {{ rack.site }}{% if rack.location %} / {{ rack.location }}{% endif %}</span></h5>
<span><a data-ce-all>Alle</a> · <a data-ce-none>Keine</a></span>
<span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span>
</div>
<div class="ce-photos">
{% for a in atts %}
@@ -167,18 +168,18 @@
</div>
<div class="card ce-card mt-3" data-ce-depends="topology">
<h2 class="card-header d-flex justify-content-between align-items-center">
<span><i class="mdi mdi-sitemap"></i> Topologie</span>
<span><i class="mdi mdi-sitemap"></i> {% trans "Topology" %}</span>
{% if perms.netbox_customer_export.view_topologysymbol %}
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-sm btn-outline-secondary" target="_blank"><i class="mdi mdi-shape-outline"></i> Symbole verwalten</a>
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-sm btn-outline-secondary" target="_blank"><i class="mdi mdi-shape-outline"></i> {% trans "Manage symbols" %}</a>
{% endif %}
</h2>
<div class="card-body">
<div class="ce-label mt-0">Umfang</div>
<div class="ce-label mt-0">{{ form.topo_scope.label }}</div>
{% include 'netbox_customer_export/_pills.html' with field=form.topo_scope %}
<div class="form-text mb-2">„Lokationsübersicht“ zeigt alle Lokationen eines Standorts und die Kabel zwischen ihnen, vom Serverraum bis zur letzten Unterverteilung. „Je Rack“ zeigt jedes Rack einzeln. Verbundene Geräte außerhalb erscheinen gestrichelt.</div>
<div class="ce-label">Beschriftung</div>
<div class="form-text mb-2">{% trans "“Location overview” shows all locations of a site and the cables between them, from the server room to the last sub-distribution. “Cross-site” combines all sites in one diagram to show how buildings and their locations are connected. “Per rack” shows each rack separately. Connected devices outside appear dashed." %}</div>
<div class="ce-label">{{ form.topo_details.label }}</div>
{% include 'netbox_customer_export/_pills.html' with field=form.topo_details %}
<div class="ce-label">Weiteres</div>
<div class="ce-label">{% trans "More" %}</div>
<label class="ce-switch">{{ form.topo_external }} {{ form.topo_external.label }}</label>
<label class="ce-switch">{{ form.topo_isolated }} {{ form.topo_isolated.label }}</label>
</div>
@@ -187,8 +188,8 @@
</div>
<div class="ce-actions mt-3">
<a href="{{ object.get_absolute_url }}" class="btn btn-outline-secondary">Abbrechen</a>
<button class="btn btn-primary"><i class="mdi mdi-download"></i> Dokument erstellen</button>
<a href="{{ object.get_absolute_url }}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
<button class="btn btn-primary"><i class="mdi mdi-download"></i> {% trans "Create document" %}</button>
</div>
</form>
@@ -1,20 +1,21 @@
{% extends 'generic/_base.html' %}
{% load i18n %}
{% load form_helpers %}
{% block title %}Kundendokumentation{% endblock %}
{% block title %}{% trans "Customer Documentation" %}{% endblock %}
{% block content %}
<form method="post" class="container-fluid my-3">
{% csrf_token %}
<div class="card">
<h2 class="card-header">Scope wählen</h2>
<h2 class="card-header">{% trans "Select scope" %}</h2>
<div class="card-body">
<p class="text-muted">Genau eines der Felder ausfüllen.</p>
<p class="text-muted">{% trans "Fill in exactly one of the fields." %}</p>
{% if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{% endif %}
{% render_field form.site %}
{% render_field form.location %}
{% render_field form.tenant %}
{% render_field form.tenantgroup %}
</div>
<div class="card-footer text-end"><button class="btn btn-primary">Weiter</button></div>
<div class="card-footer text-end"><button class="btn btn-primary">{% trans "Continue" %}</button></div>
</div>
</form>
{% endblock %}
@@ -1,16 +1,17 @@
{% extends 'generic/_base.html' %}
{% block title %}Symbol-Zuordnung löschen{% endblock %}
{% load i18n %}
{% block title %}{% trans "Delete symbol assignment" %}{% endblock %}
{% block content %}
<form method="post" class="mt-3">
{% csrf_token %}
<div class="card border-danger">
<div class="card-body">
<p>Soll die Symbol-Zuordnung für <strong>{{ object.target_label }} {{ object }}</strong> gelöscht werden?
Danach gilt wieder die automatische Erkennung. Ein hochgeladenes Icon wird ebenfalls entfernt.</p>
<p>{% blocktrans trimmed with label=object.target_label %}Delete the symbol assignment for <strong>{{ label }} {{ object }}</strong>?
Automatic detection applies again afterwards. An uploaded icon will be removed as well.{% endblocktrans %}</p>
</div>
<div class="card-footer text-end">
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> Löschen</button>
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> {% trans "Delete" %}</button>
</div>
</div>
</form>
@@ -1,6 +1,7 @@
{% extends 'generic/_base.html' %}
{% load i18n %}
{% load form_helpers %}
{% block title %}{% if object.pk %}Symbol für {{ object }}{% else %}Neue Symbol-Zuordnung{% endif %}{% endblock %}
{% block title %}{% if object.pk %}{% blocktrans %}Symbol for {{ object }}{% endblocktrans %}{% else %}{% trans "New symbol assignment" %}{% endif %}{% endblock %}
{% block content %}
<style>
.ce-kinds { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: .5rem; }
@@ -19,9 +20,9 @@
<div class="row g-3">
<div class="col-lg-4">
<div class="card h-100">
<h2 class="card-header"><i class="mdi mdi-link-variant"></i> Gilt für</h2>
<h2 class="card-header"><i class="mdi mdi-link-variant"></i> {% trans "Applies to" %}</h2>
<div class="card-body">
<p class="text-muted small">Entweder einen Gerätetyp <em>oder</em> eine Geräterolle wählen. Gerätetyp hat Vorrang.</p>
<p class="text-muted small">{% blocktrans trimmed %}Select either a device type <em>or</em> a device role. The device type takes precedence.{% endblocktrans %}</p>
{% render_field form.device_type %}
{% render_field form.role %}
</div>
@@ -29,7 +30,7 @@
</div>
<div class="col-lg-8">
<div class="card">
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> Symbol</h2>
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> {% trans "Symbol" %}</h2>
<div class="card-body">
<div class="ce-kinds mb-3">
{% for radio in form.kind %}
@@ -44,12 +45,12 @@
</div>
{% for e in form.kind.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
<label class="form-label" for="{{ form.icon.id_for_label }}">Eigenes Icon (optional)</label>
<label class="form-label" for="{{ form.icon.id_for_label }}">{% trans "Custom icon (optional)" %}</label>
<div class="d-flex gap-3 align-items-start">
{% if object.icon %}<img src="{{ object.icon.url }}" class="ce-icon-preview" alt="Aktuelles Icon">{% endif %}
{% if object.icon %}<img src="{{ object.icon.url }}" class="ce-icon-preview" alt="{% trans "Current icon" %}">{% endif %}
<div class="flex-grow-1">
{{ form.icon }}
<div class="form-text">{{ form.icon.help_text }} Ist kein Symbol gewählt, bestimmt die Automatik die Ebene im Diagramm.</div>
<div class="form-text">{{ form.icon.help_text }} {% trans "If no symbol is selected, automatic detection determines the level in the diagram." %}</div>
{% for e in form.icon.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
</div>
</div>
@@ -58,8 +59,8 @@
</div>
</div>
<div class="d-flex justify-content-end gap-2 mt-3">
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> Speichern</button>
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> {% trans "Save" %}</button>
</div>
</form>
{% endblock %}
@@ -1,9 +1,10 @@
{% extends 'generic/_base.html' %}
{% block title %}Topologie-Symbole{% endblock %}
{% load i18n %}
{% block title %}{% trans "Topology Symbols" %}{% endblock %}
{% block controls %}
{% if perms.netbox_customer_export.add_topologysymbol %}
<div class="btn-list">
<a href="{% url 'plugins:netbox_customer_export:symbol_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> Zuordnung hinzufügen</a>
<a href="{% url 'plugins:netbox_customer_export:symbol_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> {% trans "Add assignment" %}</a>
</div>
{% endif %}
{% endblock %}
@@ -19,28 +20,28 @@
<div class="row g-3 mt-1">
<div class="col-xl-7">
<div class="card mb-3">
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> Zuordnungen je Gerätetyp</h2>
{% include 'netbox_customer_export/_symbol_table.html' with rows=types empty="Noch keine Gerätetypen zugeordnet." %}
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> {% trans "Assignments per device type" %}</h2>
{% include 'netbox_customer_export/_symbol_table.html' with rows=types empty=_("No device types assigned yet.") %}
</div>
<div class="card">
<h2 class="card-header"><i class="mdi mdi-tag-outline"></i> Zuordnungen je Geräterolle</h2>
{% include 'netbox_customer_export/_symbol_table.html' with rows=roles empty="Noch keine Geräterollen zugeordnet." %}
<h2 class="card-header"><i class="mdi mdi-tag-outline"></i> {% trans "Assignments per device role" %}</h2>
{% include 'netbox_customer_export/_symbol_table.html' with rows=roles empty=_("No device roles assigned yet.") %}
</div>
</div>
<div class="col-xl-5">
<div class="card mb-3">
<h2 class="card-header"><i class="mdi mdi-information-outline"></i> So wird das Symbol bestimmt</h2>
<h2 class="card-header"><i class="mdi mdi-information-outline"></i> {% trans "How the symbol is determined" %}</h2>
<div class="card-body">
<ol class="mb-0">
<li><strong>Gerätetyp</strong>-Zuordnung (eigenes Icon oder Symbol)</li>
<li><strong>Geräterolle</strong>-Zuordnung</li>
<li><strong>Automatisch</strong> anhand von Rolle, Modell und Hersteller, z.B. „Switch“, „Firewall“, „Sophos“, „Access Point“.
Patchpanels, Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet.</li>
<li>{% blocktrans trimmed %}<strong>Device type</strong> assignment (custom icon or symbol){% endblocktrans %}</li>
<li>{% blocktrans trimmed %}<strong>Device role</strong> assignment{% endblocktrans %}</li>
<li>{% blocktrans trimmed %}<strong>Automatic</strong> based on role, model and manufacturer, e.g. “Switch”, “Firewall”, “Sophos”, “Access Point”.
Patch panels, power strips, PDUs and UPSs are hidden automatically.{% endblocktrans %}</li>
</ol>
</div>
</div>
<div class="card">
<h2 class="card-header"><i class="mdi mdi-view-grid-outline"></i> Eingebaute Symbole</h2>
<h2 class="card-header"><i class="mdi mdi-view-grid-outline"></i> {% trans "Built-in symbols" %}</h2>
<div class="card-body">
<div class="ce-gallery">
{% for key, label, url in builtin %}
+88 -40
View File
@@ -4,6 +4,9 @@ from collections import OrderedDict, defaultdict, deque
from dataclasses import dataclass, field
from io import BytesIO
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from .symbols import KINDS, SymbolResolver, builtin_icon
MAX_PER_ROW = 12 # breitere Zeilen werden umgebrochen
@@ -29,6 +32,7 @@ class Edge:
b: str
labels: list = field(default_factory=list)
summary: str = "" # feste Beschriftung statt Port-Namen (z.B. Lokationsübersicht)
wireless: bool = False # nur Funkstrecken (WirelessLink) – blau gepunktet
@dataclass
@@ -87,7 +91,7 @@ def build_graphs(scope, opts, per="site"):
cache = getattr(scope, "_topology_cache", None)
if cache is None:
cache = scope._topology_cache = _collect(scope, opts)
by_pk, drawn, links, external = cache
by_pk, drawn, links, external, wireless = cache
groups = OrderedDict()
for pk in drawn:
@@ -103,7 +107,7 @@ def build_graphs(scope, opts, per="site"):
def context(d):
"""Untertitel eines externen Geräts: wo es steht."""
if per == "rack":
return [f"Rack {d.rack}" if d.rack else str(d.site)]
return [_("Rack %(name)s") % {"name": d.rack} if d.rack else str(d.site)]
return [str(d.site)]
graphs = []
@@ -127,17 +131,17 @@ def build_graphs(scope, opts, per="site"):
kind, icon = drawn[d.pk]
other = Node(nid, d.name or str(d), kind, icon, context(d), external=True)
nodes[nid] = Node(**{**other.__dict__})
edges.append(Edge(a, b, labels))
edges.append(Edge(a, b, labels, wireless=(a, b) in wireless))
if not opts.get("topo_isolated"):
linked = {n for e in edges for n in (e.a, e.b)}
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
if nodes:
_layout(nodes, edges)
if per == "site":
title = f"Standort {group}"
title = _("Site %(name)s") % {"name": group}
else:
where = " / ".join(str(x) for x in (group.site, group.location) if x)
title = f"Rack {group.name} ({where})"
title = _("Rack %(name)s (%(where)s)") % {"name": group.name, "where": where}
graphs.append(Graph(title, nodes, edges))
return graphs
@@ -145,6 +149,7 @@ def build_graphs(scope, opts, per="site"):
def _collect(scope, opts):
"""Geräte, Symbole und Verbindungen (Kabelpfade) des Scopes einmalig einlesen."""
from dcim.models import Interface
from django.db.models import Q
resolver = SymbolResolver()
devices = list(
@@ -159,11 +164,12 @@ def _collect(scope, opts):
drawn[d.pk] = (kind, icon)
by_pk = {d.pk: d for d in devices}
# Verbindungen: vollständige Kabelpfade (auch über Patchpanels) zwischen Interfaces
# Verbindungen: vollständige Kabelpfade (auch über Patchpanels) und Funkstrecken zwischen Interfaces
links = defaultdict(list) # (a, b) -> ["Gi1/0/1 – eth0", …]
kinds = defaultdict(set) # (a, b) -> {"cable", "wireless"}
external = {} # node_id -> Node-Vorlage
ifaces = scope.restrict(
Interface.objects.filter(device_id__in=list(drawn), cable__isnull=False)
Interface.objects.filter(Q(cable__isnull=False) | Q(wireless_link__isnull=False), device_id__in=list(drawn))
).select_related("device")
for iface in ifaces:
try:
@@ -204,57 +210,74 @@ def _collect(scope, opts):
label = " – ".join(reversed(label.split(" – ")))
if label not in links[key]:
links[key].append(label)
kinds[key].add("cable" if iface.cable_id else "wireless")
return by_pk, drawn, links, external
wireless = {k for k, v in kinds.items() if v == {"wireless"}}
return by_pk, drawn, links, external, wireless
def build_location_graphs(scope, opts):
def build_location_graphs(scope, opts, combined=False):
"""Lokationsübersicht: ein Graph je Standort, Knoten = Lokationen, Linien = Kabel zwischen Lokationen.
Mit `combined=True` entsteht ein einziger standortübergreifender Graph über alle Lokationen im Scope, an
jedem Knoten steht der Standort – so sieht man, wie Gebäude und ihre Lokationen untereinander verbunden sind.
Gezählt werden physische Kabel (Interfaces, Front- und Rear-Ports), deren Enden in verschiedenen Lokationen
liegen – typischerweise LWL-/Kupfer-Trunks vom Serverraum zu den Unterverteilungen. Lokationen mit
Firewall/Router/Core stehen oben, die Ebenen darunter folgen der Verkabelung.
"""
from dcim.models import FrontPort, Interface, RearPort
from django.db.models import Q
resolver = SymbolResolver()
devices = list(
scope.devices().filter(location__isnull=False)
scope.devices()
.select_related("role", "device_type__manufacturer", "site", "location__parent", "rack")
.order_by("site__name", "location__name")
)
if not devices:
return []
by_pk = {d.pk: d for d in devices}
loc_of = {d.pk: d.location for d in devices}
def node_of(d):
"""Lokation des Geräts – Geräte ohne Lokation (z.B. Richtfunk-APs am Dach) hängen am Standort selbst."""
return f"l{d.location_id}" if d.location_id else f"s{d.site_id}"
nid_of = {d.pk: node_of(d) for d in devices}
# Ebene je Lokation = „höchstes“ Gerät darin (Firewall/Core oben, reine Verteiler darunter)
tier, racks, count = {}, defaultdict(set), defaultdict(int)
for d in devices:
kind, _icon = resolver.resolve(d)
t = KINDS.get(kind, ("", 3))[1] if kind else 3
tier[d.location_id] = min(tier.get(d.location_id, 9), t)
count[d.location_id] += 1
nid = nid_of[d.pk]
tier[nid] = min(tier.get(nid, 9), t)
count[nid] += 1
if d.rack_id:
racks[d.location_id].add(d.rack_id)
racks[nid].add(d.rack_id)
cables = {} # cable.pk -> (Knoten a, Knoten b, Kabel)
cables = {} # ("c"|"w", pk) -> (Knoten a, Knoten b, Kabel oder WirelessLink)
outside = {} # node_id -> Node (andere Standorte / Provider)
for model in (Interface, FrontPort, RearPort):
ports = scope.restrict(model.objects.filter(device_id__in=list(by_pk), cable__isnull=False)).select_related("cable")
cond = Q(cable__isnull=False)
if model is Interface:
cond |= Q(wireless_link__isnull=False)
ports = scope.restrict(model.objects.filter(cond, device_id__in=list(by_pk))).select_related("cable")
for port in ports:
if port.cable_id in cables:
link = port.cable if port.cable_id else port.wireless_link
link_key = ("c", port.cable_id) if port.cable_id else ("w", port.wireless_link_id)
if link_key in cables:
continue
try:
peers = port.link_peers or []
except Exception: # noqa: BLE001
continue
a = f"l{loc_of[port.device_id].pk}"
a = nid_of[port.device_id]
for peer in peers:
peer_dev = getattr(peer, "device", None)
if peer_dev is not None:
if peer_dev.pk in by_pk:
b = f"l{loc_of[peer_dev.pk].pk}"
b = nid_of[peer_dev.pk]
elif not opts.get("topo_external"):
continue
else:
@@ -271,7 +294,7 @@ def build_location_graphs(scope, opts):
else:
continue
if a != b:
cables[port.cable_id] = (a, b, port.cable)
cables[link_key] = (a, b, link)
break
links = defaultdict(list)
@@ -279,21 +302,31 @@ def build_location_graphs(scope, opts):
links[tuple(sorted((a, b)))].append(cable)
sites = OrderedDict()
all_locs = {}
all_locs = {} # node_id -> (Name, Standort)
for d in devices:
sites.setdefault(d.site, OrderedDict())[d.location_id] = d.location
all_locs[f"l{d.location_id}"] = d.location
nid = nid_of[d.pk]
sites.setdefault(None if combined else d.site, OrderedDict())[nid] = d
all_locs[nid] = (d.location.name if d.location_id else str(d.site), d.site)
graphs = []
for site, locations in sites.items():
nodes = OrderedDict()
for loc in locations.values():
sub = [str(loc.parent)] if loc.parent_id else []
n_racks, n_dev = len(racks[loc.pk]), count[loc.pk]
parts = [f"{n_racks} Rack" + ("s" if n_racks != 1 else "")] if n_racks else []
parts.append(f"{n_dev} Gerät" + ("e" if n_dev != 1 else ""))
for nid, d in locations.items():
loc = d.location
if loc is not None:
name = loc.name
where = [str(loc.site)] if combined else []
if loc.parent_id:
where.append(str(loc.parent))
else:
name = str(d.site)
where = [_("without location")]
sub = [" / ".join(where)] if where else []
n_racks, n_dev = len(racks[nid]), count[nid]
parts = [ngettext("%(n)d rack", "%(n)d racks", n_racks) % {"n": n_racks}] if n_racks else []
parts.append(ngettext("%(n)d device", "%(n)d devices", n_dev) % {"n": n_dev})
sub.append(" · ".join(parts))
nodes[f"l{loc.pk}"] = Node(f"l{loc.pk}", loc.name, "location", builtin_icon("location"), sub, tier=tier[loc.pk])
nodes[nid] = Node(nid, name, "location", builtin_icon("location"), sub, tier=tier[nid])
members = set(nodes)
edges = []
for (a, b), lst in links.items():
@@ -304,24 +337,31 @@ def build_location_graphs(scope, opts):
continue
tpl = outside.get(nid)
if tpl is None: # Lokation im Scope, aber an einem anderen Standort
loc = all_locs[nid]
tpl = Node(nid, loc.name, "location", builtin_icon("location"), [str(loc.site)], external=True)
name, loc_site = all_locs[nid]
tpl = Node(nid, name, "location", builtin_icon("location"), [str(loc_site)], external=True)
nodes[nid] = Node(**{**tpl.__dict__})
edges.append(Edge(a, b, [str(c) for c in lst], summary=_cable_summary(lst)))
edges.append(Edge(
a, b, [str(c) for c in lst], summary=_cable_summary(lst),
wireless=all(c._meta.model_name == "wirelesslink" for c in lst),
))
if not opts.get("topo_isolated"):
linked = {n for e in edges for n in (e.a, e.b)}
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
if nodes:
_layout(nodes, edges)
graphs.append(Graph(f"Standort {site}", nodes, edges))
title = _("All sites") if combined else _("Site %(name)s") % {"name": site}
graphs.append(Graph(title, nodes, edges))
return graphs
def _cable_summary(cables):
"""„2× SMF, 4× CAT6a“ – Kabel ohne Typ zählen als „Kabel“."""
"""„2× SMF, 4× CAT6a, 1× Funk“ – Kabel ohne Typ zählen als „Kabel“, Funkstrecken als „Funk“."""
types = defaultdict(int)
for c in cables:
types[c.get_type_display() if c.type else "Kabel"] += 1
if c._meta.model_name == "wirelesslink":
types[_("Wireless")] += 1
else:
types[c.get_type_display() if c.type else _("Cable")] += 1
return ", ".join(f"{n}× {t}" for t, n in sorted(types.items(), key=lambda x: -x[1]))
@@ -424,8 +464,12 @@ def _edge_text(graph, e, show_ports):
return e.summary
if show_ports:
labels = _oriented(graph, e)
return labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
return f"{len(e.labels)}×" if len(e.labels) > 1 else None
text = labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
return f"{_('Wireless')}: {text}" if e.wireless else text
count = f"{len(e.labels)}×" if len(e.labels) > 1 else ""
if e.wireless:
return f"{count} {_('Wireless')}".strip()
return count or None
# --- PNG ----------------------------------------------------------------------
@@ -435,6 +479,7 @@ PALETTE = [
(23, 150, 170), (140, 86, 75), (188, 150, 20), (200, 80, 160), (90, 90, 90),
]
EXTERNAL = (160, 160, 160)
WIRELESS = (30, 136, 229) # Funkstrecken: blau, gepunktet
def _font(size, bold=False):
@@ -577,7 +622,8 @@ def render_png(graph, show_ports=False, scale=2):
line([(min(xs), ly), (max(xs), ly)], col, dashed=u.external)
for c, e, ex, stack_pos in entries:
dashed = u.external or c.external
line([(ex, ly), (ex, c.y - 2)], EXTERNAL if dashed else col, w=3 if len(e.labels) > 1 else 2, dashed=dashed)
drop_col = WIRELESS if e.wireless else EXTERNAL if dashed else col
line([(ex, ly), (ex, c.y - 2)], drop_col, w=3 if len(e.labels) > 1 else 2, dashed=dashed or e.wireless)
if min(xs) < ex < max(xs): # Abzweig auf der Schiene markieren
d.ellipse([(ex - 2.5) * S, (ly - 2.5) * S, (ex + 2.5) * S, (ly + 2.5) * S], fill=col)
text = _edge_text(graph, e, show_ports)
@@ -590,7 +636,8 @@ def render_png(graph, show_ports=False, scale=2):
a, b = nodes[e.a], nodes[e.b]
ly = gap["top"] + gap["lane_of"][("s", i)] * LANE
dashed = a.external or b.external
line([(a.x, a.y - 2), (a.x, ly), (b.x, ly), (b.x, b.y - 2)], EXTERNAL if dashed else (70, 70, 70), dashed=dashed)
col = WIRELESS if e.wireless else EXTERNAL if dashed else (70, 70, 70)
line([(a.x, a.y - 2), (a.x, ly), (b.x, ly), (b.x, b.y - 2)], col, dashed=dashed or e.wireless)
text = _edge_text(graph, e, show_ports)
if text:
labels.append((text, (a.x + b.x) / 2, ly, "mm"))
@@ -602,7 +649,8 @@ def render_png(graph, show_ports=False, scale=2):
left, right = (a, b) if a.x < b.x else (b, a)
line(
[(left.x + ICON / 2 + 4, cy), (right.x - ICON / 2 - 4, cy)],
EXTERNAL if dashed else (70, 70, 70), w=3 if len(e.labels) > 1 else 2, dashed=dashed,
WIRELESS if e.wireless else EXTERNAL if dashed else (70, 70, 70),
w=3 if len(e.labels) > 1 else 2, dashed=dashed or e.wireless,
)
text = _edge_text(graph, e, show_ports)
if text:
+3 -2
View File
@@ -3,6 +3,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from django.utils.formats import date_format
from django.utils.text import slugify
from django.views import View
@@ -67,7 +68,7 @@ class ExportView(LoginRequiredMixin, View):
blocks=blocks,
meta={
"author": opts.get("author") or request.user.get_full_name() or request.user.username,
"date": timezone.localtime().strftime("%d.%m.%Y"),
"date": date_format(timezone.localdate(), "SHORT_DATE_FORMAT"),
},
branding=get_branding(opts["branding"]),
)
@@ -79,6 +80,6 @@ class ExportView(LoginRequiredMixin, View):
response = HttpResponse(content, content_type=content_type)
if ext != "html":
filename = f"{slugify(opts['title']) or 'dokumentation'}_{timezone.localdate():%Y%m%d}.{ext}"
filename = f"{slugify(opts['title']) or 'documentation'}_{timezone.localdate():%Y%m%d}.{ext}"
response["Content-Disposition"] = f'attachment; filename="{filename}"'
return response
+7 -3
View File
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
[project]
name = "netbox-customer-export"
version = "0.16.0"
description = "NetBox-Plugin: Kundendokumentation (PDF/Word) für Standorte, Lokationen, Mandanten und Mandantengruppen"
version = "0.19.1"
description = "NetBox plugin: customer documentation (PDF/Word) for sites, locations, tenants and tenant groups"
readme = "README.md"
requires-python = ">=3.10"
license = { text = "Apache-2.0" }
@@ -20,4 +20,8 @@ all = ["weasyprint>=62", "python-docx>=1.1", "cairosvg>=2.7"]
include = ["netbox_customer_export*"]
[tool.setuptools.package-data]
netbox_customer_export = ["templates/**/*.html"]
netbox_customer_export = [
"templates/**/*.html",
"locale/*/LC_MESSAGES/*.po",
"locale/*/LC_MESSAGES/*.mo",
]
+42
View File
@@ -0,0 +1,42 @@
"""Keeps the README compatibility table in sync with the PluginConfig version range."""
import ast
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def plugin_versions():
tree = ast.parse((ROOT / "netbox_customer_export" / "__init__.py").read_text())
values = {}
for node in ast.walk(tree):
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in ("min_version", "max_version"):
values[target.id] = node.value.value
return values["min_version"], values["max_version"]
def readme_range(max_version):
# "4.7.99" is documented as "4.7.x"
major_minor, patch = max_version.rsplit(".", 1)
return major_minor + ".x" if patch == "99" else max_version
class MetadataTest(unittest.TestCase):
def test_readme_matches_plugin_config(self):
min_version, max_version = plugin_versions()
expected = f"`{min_version}` – `{readme_range(max_version)}`"
readme = (ROOT / "README.md").read_text()
self.assertIn(f"| **NetBox** | {expected} |", readme)
self.assertRegex(readme, re.escape(f"- NetBox {expected}"))
def test_package_ships_translations(self):
pyproject = (ROOT / "pyproject.toml").read_text()
self.assertIn("locale/*/LC_MESSAGES/*.mo", pyproject)
self.assertTrue((ROOT / "netbox_customer_export" / "locale" / "de" / "LC_MESSAGES" / "django.mo").exists())
if __name__ == "__main__":
unittest.main()