Compare commits

...
12 Commits
Author SHA1 Message Date
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 4405a65653 feat: optional floor plans from NetBox-FloorPlan
New section 'Raumpläne' renders floor plans of netbox_floorplanner in
scope as standalone SVG (Pillow PNG fallback for Word) with room size,
background image and placed racks/devices. The plugin is only accessed
via the app registry, so there is no hard dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:13:19 +01:00
MrBlakeandClaude Opus 5.5 ca29980aa6 fix: no Netbox-Utilities mentions in customer documents
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:13:41 +01:00
MrBlakeandClaude Opus 5.5 55c70814c3 feat: CPU & RAM from Netbox-Utilities in device tables and clusters
Device tables get optional CPU and RAM columns. Clusters show physical
cores/threads and host RAM with vCPU-per-core ratio and RAM allocation.
Also fixes decimal formatting of vCPU and rack units (245.00, HE 40.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:29:37 +01:00
MrBlakeandClaude Opus 5.5 4ec96bf65d feat: location overview topology instead of per-location cabling
One diagram per site with locations as nodes and the physical cables
between them, summarised by count and cable type, to follow the cabling
from the server room to the last sub-distribution.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 15:48:39 +01:00
MrBlakeandClaude Opus 5.5 59ffd2a4b5 feat: per-location cabling topology including patch panels
Draws every cable hop by hop (interfaces, front and rear ports) per
top-level location, so trunks from switches over patch panels to
sub-distributions become visible. Adds a patch panel symbol.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 15:41:15 +01:00
MrBlakeandClaude Opus 5.5 cd4357f417 fix: always show rack photo card with hint when none found
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 15:20:43 +01:00
MrBlakeandClaude Opus 5.5 c888a65180 feat: rack photo appendix and virtualization cluster section
Rack image attachments can be picked with thumbnails in the export form and
are placed in an appendix, linked from below each rack elevation (Word:
internal hyperlinks to bookmarks). New section lists clusters with hosts and
summed VM resources, counting only VMs inside the export scope.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 15:17:17 +01:00
MrBlake 74dfa0ec61 Merge branch 'main' of https://git.mrblake.cc/MrBlake/NetBox-Customer-Export 2026-10-28 14:53:26 +01:00
MrBlakeandClaude Opus 5.5 2c0e026cb9 fix: disk table fits page like other tables
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 13:06:30 +01:00
19 changed files with 1122 additions and 54 deletions

No files matched your search

+39 -3
View File
@@ -28,7 +28,7 @@ Before exporting, the technician selects which content the document contains:
| Group | Content |
|---|---|
| General | Overview & site data (address, location tree, key figures), contacts |
| Infrastructure | Racks by site → location with rack elevation (front/rear, optionally with device images as in NetBox) and occupancy list, devices by **selectable device roles** (servers, switches, APs, routers …) with **selectable columns**, power, VMs, **disks & RAID** from [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) (if installed) |
| Infrastructure | Racks by site → location with rack elevation (front/rear, optionally with device images as in NetBox) occupancy list and optional **rack photos** in an appendix, devices by **selectable device roles** (servers, switches, APs, routers …) with **selectable columns**, power, **virtualization clusters** with resources, VMs, **disks & RAID** from [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) (if installed), **floor plans** from [NetBox-FloorPlan](https://git.mrblake.cc/MrBlake/NetBox-FloorPlan2.0) (if installed) |
| Network | VRFs (incl. RTs), prefixes by VRF, VLANs, IP addresses (detailed), WLANs/SSIDs, circuits, **network topology** |
| Contracts & licenses | Licenses from [NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM) (detected automatically) or another license plugin (e.g. `netbox-lifecycle`) |
@@ -257,7 +257,9 @@ style of Cisco Packet Tracer:
- Links come from NetBox **cable paths**; paths through patch panels are traced to the end device.
- 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) 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.
- **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 **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).
- Selectable labels: management IP, model, ports on links.
@@ -271,7 +273,7 @@ button on device type and device role pages):
3. otherwise **automatic**, first by role, then by model and manufacturer
Built-in symbols: internet/provider, modem/NTU, firewall, router, layer-3
switch, switch, radio link, WLAN controller, PoE injector, access point, server,
switch, switch, radio link, patch panel, WLAN controller, PoE injector, access point, server,
storage/SAN, NAS, tape library, UPS/ATS, PBX, IP phone, PC/client, printer,
camera and "other".
@@ -306,6 +308,40 @@ slot, status, type, model, size, serial number, firmware, RAID group, optionally
expired/expiring soon, too old – thresholds from the Utilities configuration). Removed disks (history) are not shown.
Without the plugin the section stays empty.
### Floor plans (NetBox-FloorPlan)
If [NetBox-FloorPlan](https://git.mrblake.cc/MrBlake/NetBox-FloorPlan2.0) (`netbox_floorplanner`) is installed, the
**Floor plans** section (off by default) shows every floor plan in scope (site, location, or – for tenants – plans of the
tenant or containing its racks/devices) as a full-width drawing with room size, the background image (JPEG/PNG), and a
table of the placed racks and devices. The plugin is optional and never imported directly; without it the section stays empty.
For Word the drawing is converted with cairosvg, otherwise a simplified Pillow rendering is used.
### Rack photos
Images attached to racks in NetBox (*Attach an image*) show up as thumbnails in the
**Rack photos** card of the export form, grouped by rack. Selected photos are
placed in an appendix at the end of the document. Below each rack elevation a link
points to that rack's photos, and each appendix entry links back to the rack. Photos
are rotated according to EXIF and scaled down to 1600 px. In Word the links are internal
hyperlinks to bookmarks.
### Virtualization clusters
The **Virtualization clusters** section (off by default) lists every cluster with hosts
or VMs in scope: an overview table, then per cluster type, group, status, tenant and the
summed vCPU, RAM and disk of its VMs, plus a host table with VMs, vCPU and RAM per host.
Only VMs inside the export scope are counted, so a tenant export does not reveal other
tenants' VMs on a shared cluster.
### CPU & RAM (Netbox-Utilities)
If [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) with CPU & RAM is installed:
- Device tables offer the columns **CPU** (model, count, cores/threads) and **RAM** (total, modules, type and speed).
- The **Virtualization clusters** section adds the physical cores/threads and RAM of the hosts and shows the overcommitment: vCPU per physical core (e.g. `2,6 : 1`) and assigned VM RAM as a percentage of host RAM, per cluster and per host.
RAM is shown in binary units like in Netbox-Utilities (1 GB = 1024 MB), so VM and host values are comparable. Without the plugin the columns stay empty and the cluster section shows VM totals only.
### Rack elevations
By default the plugin uses NetBox's own `dcim.svg.RackElevationSVG` in-process
+1 -1
View File
@@ -6,7 +6,7 @@ class CustomerExportConfig(PluginConfig):
name = "netbox_customer_export"
verbose_name = _("Customer Export")
description = _("Export customer documentation as PDF or Word")
version = "0.11.0"
version = "0.18.0"
author = "Claude"
base_url = "customer-export"
min_version = "4.6.8"
+12 -5
View File
@@ -10,7 +10,7 @@ EMPTY = "—"
@dataclass
class Block:
kind: str # heading | paragraph | table | kv | images | pagebreak
kind: str # heading | paragraph | ref | table | kv | images | pagebreak | landscape
level: int = 0
text: str = ""
headers: list = field(default_factory=list)
@@ -48,6 +48,11 @@ def P(text):
return Block("paragraph", text=str(text))
def REF(text, target, prefix=""):
"""Interner Verweis auf eine Überschrift (target = deren anchor); prefix bleibt unverlinkt."""
return Block("ref", text=str(text), anchor=target, rows=[prefix])
def T(headers, rows):
return Block("table", headers=[str(h) for h in headers], rows=[[fmt(c) for c in r] for r in rows])
@@ -57,18 +62,20 @@ def KV(pairs, skip_empty=True):
return Block("kv", rows=rows)
def IMAGES(images, wide=False):
"""images: Liste von (svg_string oder None, caption, png_bytes_oder_None)."""
def IMAGES(images, wide=False, photos=False):
"""images: Liste von (svg_string oder None, caption, png_bytes_oder_None). Statt PNG geht auch JPEG."""
out = []
for svg, caption, png in images:
if svg:
data_uri = "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii")
elif png:
data_uri = "data:image/png;base64," + base64.b64encode(png).decode("ascii")
mime = "image/jpeg" if png[:2] == bytes((0xFF, 0xD8)) else "image/png"
data_uri = f"data:{mime};base64," + base64.b64encode(png).decode("ascii")
else:
continue
out.append({"svg": svg, "png": png, "caption": caption, "data_uri": data_uri})
return Block("images", images=out, level=1 if wide else 0) # level=1: volle Seitenbreite
# level=1: volle Seitenbreite, level=2: Fotos (zwei je Zeile)
return Block("images", images=out, level=2 if photos else 1 if wide else 0)
def LANDSCAPE(headings, png):
+7 -6
View File
@@ -55,7 +55,7 @@ def disk_blocks(scope, opts):
by_device.setdefault(disk.device, []).append(disk)
show_installed = bool(opts.get("disk_install_date"))
headers = [_("Slot"), _("Status"), _("Type"), _("Manufacturer / model"), _("Size"), _("Serial number"), _("Firmware"), "RAID"]
headers = [_("Slot"), _("Status"), _("Disk"), _("Size"), _("Serial number"), "RAID"]
headers += [_("Installed")] * show_installed + [_("Warranty until"), _("Notes")]
blocks = []
for device, items in by_device.items():
@@ -91,12 +91,13 @@ def disk_blocks(scope, opts):
row = [
_slot(d),
d.get_status_display(),
" / ".join(x for x in (d.get_disk_type_display(), d.get_interface_display()) if x),
" ".join(x for x in (d.manufacturer, d.model) if x),
"\n".join(x for x in (
" ".join(x for x in (d.manufacturer, d.model) if x),
" / ".join(x for x in (d.get_disk_type_display(), d.get_interface_display()) if x),
) if x),
fmt(d.capacity_gb) if d.capacity_gb else None,
d.serial,
d.firmware,
d.raid_group,
"\n".join(x for x in (d.serial, f"FW {d.firmware}" if d.firmware else "") if x),
d.raid_group.name if d.raid_group_id else None,
]
if show_installed:
row.append(_date(getattr(d, "install_date", None)))
+278
View File
@@ -0,0 +1,278 @@
"""Raumpläne aus dem Plugin NetBox-FloorPlan (netbox_floorplanner.FloorPlan / FloorPlanItem).
Optional: Ohne das Plugin liefert ``is_installed()`` False und der Abschnitt bleibt leer.
Es wird nichts aus ``netbox_floorplanner`` importiert, Modelle kommen nur über die App-Registry.
Das SVG ist eigenständig (feste Farben, eingebettetes Hintergrundbild), damit es in PDF und Word
(cairosvg) gleich aussieht; für Word ohne cairosvg gibt es ein vereinfachtes Pillow-PNG.
"""
import base64
import math
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
APP = "netbox_floorplanner"
TYPE_COLORS = {
"area": "#22c55e", "wall": "#475569", "door": "#b45309", "window": "#0ea5e9", "column": "#64748b",
"rack": "#3b82f6", "device": "#8b5cf6", "cooling": "#06b6d4", "power": "#f59e0b", "label": "#334155",
}
FILLED = ("rack", "device", "cooling", "power")
FLOOR, WALL, MUTED = "#ffffff", "#334155", "#6c757d"
def is_installed():
if not apps.is_installed(APP):
return False
try:
apps.get_model(APP, "FloorPlan")
apps.get_model(APP, "FloorPlanItem")
except LookupError:
return False
return True
def _models():
return apps.get_model(APP, "FloorPlan"), apps.get_model(APP, "FloorPlanItem")
def floorplans(scope):
"""Raumpläne im Scope. Mandanten: Pläne des Mandanten oder mit dessen Racks/Geräten."""
FloorPlan, _ = _models()
if scope.kind == "site":
q = Q(site=scope.obj)
elif scope.kind == "location":
q = Q(location__in=scope.locations)
else:
q = Q(tenant__in=scope.tenants) | Q(items__rack__tenant__in=scope.tenants) | Q(items__device__tenant__in=scope.tenants)
qs = FloorPlan.objects.filter(q).distinct().select_related("site", "location", "tenant")
return scope.restrict(qs).order_by("site__name", "location__name", "name")
def meters(cm):
return f"{cm / 100:.2f}".rstrip("0").rstrip(".").replace(".", ",")
def _items(plan):
_, Item = _models()
return list(Item.objects.filter(floorplan=plan).select_related("rack", "device").order_by("z_index", "pk"))
def _text(item):
return item.label or (item.rack.name if item.rack_id else item.device.name if item.device_id else "")
def _shade(hex_color, f=0.7):
try:
n = int(hex_color.lstrip("#"), 16)
except ValueError:
return hex_color
return "#{:02x}{:02x}{:02x}".format(*(round(((n >> s) & 255) * f) for s in (16, 8, 0)))
def _color(item):
c = item.color or TYPE_COLORS.get(item.item_type, "#868e96")
return c if len(c) == 7 and c.startswith("#") else "#868e96"
# --- SVG ----------------------------------------------------------------------
def _item_svg(item):
x, y, w, h, t = item.x, item.y, item.width, item.height, item.item_type
cx, cy = x + w / 2, y + h / 2
color = _color(item)
sw = 'stroke-width="3"'
parts = []
if t == "area":
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="4" fill="{color}" fill-opacity="0.12" stroke="{color}" {sw} stroke-dasharray="12 6"/>')
elif t in ("wall", "door"):
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}"/>')
if t == "door":
parts.append(f'<path d="M {x + w} {y} A {w} {w} 0 0 0 {x} {y - w} L {x} {y}" fill="{color}" fill-opacity="0.08" stroke="{color}" stroke-width="2" stroke-dasharray="6 4"/>')
elif t == "window":
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{FLOOR}" stroke="{color}" {sw}/>')
elif t == "column":
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}" fill-opacity="0.35" stroke="{color}" {sw}/>'
f'<path d="M {x} {y} L {x + w} {y + h} M {x + w} {y} L {x} {y + h}" stroke="{color}" stroke-width="2"/>')
elif t in FILLED:
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="2" fill="{color}" fill-opacity="0.85" stroke="{_shade(color)}" {sw}/>')
if t == "rack":
fh = min(h * 0.12, 10)
parts.append(f'<rect x="{x}" y="{y + h - fh}" width="{w}" height="{fh}" fill="{_shade(color)}"/>')
text = _text(item)
if text:
fs = max(8, h * 0.6) if t == "label" else max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60))
fill = "#ffffff" if t in FILLED else color if t == "label" else _shade(color)
anchor, tx, ty = ("start", x + fs * 0.5, y + fs * 1.2) if t == "area" else ("middle", cx, cy)
flip = f' transform="rotate(180 {tx} {ty})"' if 90 < item.rotation % 360 <= 270 else ""
parts.append(f'<text x="{tx}" y="{ty}" dy="0.35em" font-size="{fs:.1f}" font-weight="bold" text-anchor="{anchor}" fill="{fill}"{flip}>{escape(text)}</text>')
transform = f' transform="rotate({item.rotation} {cx} {cy})"' if item.rotation else ""
return f'<g{transform}>{"".join(parts)}</g>'
def _background(plan):
"""Hintergrundbild als (Bytes, MIME) oder None."""
if not plan.background_image:
return None
try:
with plan.background_image.open("rb") as f:
data = f.read()
except Exception: # noqa: BLE001 – Datei fehlt o.Ä.: Plan ohne Hintergrund
return None
mime = "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png" if data[:4] == b"\x89PNG" else "image/webp" if data[8:12] == b"WEBP" else "image/gif"
return data, mime
def render_svg(plan, items):
width, depth = plan.width, plan.depth
fs = max(10, min(max(width, depth) * 0.025, 200))
m = fs * 2
bg = ""
if (b := _background(plan)) and b[1] in ("image/jpeg", "image/png"):
uri = f"data:{b[1]};base64," + base64.b64encode(b[0]).decode("ascii")
bg = f'<image href="{uri}" xlink:href="{uri}" x="0" y="0" width="{width}" height="{depth}" preserveAspectRatio="none" opacity="{plan.background_opacity / 100}"/>'
vw, vh = width + 2 * m, depth + 2 * m
px = 1600 / vw # feste Pixelgröße für Renderer ohne viewBox-Skalierung
return (
f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
f'width="{vw * px:.0f}" height="{vh * px:.0f}" viewBox="{-m} {-m} {vw} {vh}" font-family="DejaVu Sans, Arial, sans-serif">'
f'<rect x="{-m}" y="{-m}" width="{vw}" height="{vh}" fill="#ffffff"/>'
f'<rect x="0" y="0" width="{width}" height="{depth}" fill="{FLOOR}"/>{bg}'
f'{"".join(_item_svg(i) for i in items)}'
f'<rect x="0" y="0" width="{width}" height="{depth}" fill="none" stroke="{WALL}" stroke-width="{max(4, fs * 0.15):.1f}"/>'
f'<text x="{width / 2}" y="{-fs * 0.6}" font-size="{fs:.1f}" text-anchor="middle" fill="{MUTED}">{meters(width)} m</text>'
f'<text transform="translate({-fs * 0.6} {depth / 2}) rotate(-90)" font-size="{fs:.1f}" text-anchor="middle" fill="{MUTED}">{meters(depth)} m</text>'
f"</svg>"
)
# --- PNG (Pillow, für Word ohne cairosvg) ---------------------------------------
def _rgb(hex_color):
n = int(hex_color.lstrip("#"), 16)
return (n >> 16) & 255, (n >> 8) & 255, n & 255
def _mix(rgb, alpha, base=(255, 255, 255)):
return tuple(round(c * alpha + b * (1 - alpha)) for c, b in zip(rgb, base))
def render_png(plan, items):
from PIL import Image, ImageDraw
from .rack_png import _font
width, depth = plan.width, plan.depth
fs = max(10, min(max(width, depth) * 0.025, 200))
m = fs * 2
s = 1600 / (width + 2 * m)
img = Image.new("RGB", (round((width + 2 * m) * s), round((depth + 2 * m) * s)), "white")
if (b := _background(plan)):
try:
bgi = Image.open(BytesIO(b[0])).convert("RGB").resize((max(1, round(width * s)), max(1, round(depth * s))))
img.paste(Image.blend(Image.new("RGB", bgi.size, "white"), bgi, plan.background_opacity / 100), (round(m * s), round(m * s)))
except Exception: # noqa: BLE001
pass
d = ImageDraw.Draw(img)
def pt(px_, py_):
return (px_ + m) * s, (py_ + m) * s
for item in items:
x, y, w, h, t = item.x, item.y, item.width, item.height, item.item_type
cx, cy = x + w / 2, y + h / 2
a = math.radians(item.rotation or 0)
def rot(px_, py_):
dx, dy = px_ - cx, py_ - cy
return pt(cx + dx * math.cos(a) - dy * math.sin(a), cy + dx * math.sin(a) + dy * math.cos(a))
poly = [rot(x, y), rot(x + w, y), rot(x + w, y + h), rot(x, y + h)]
c = _rgb(_color(item))
if t == "area":
d.polygon(poly, fill=_mix(c, 0.12), outline=c, width=2)
elif t in ("wall", "door"):
d.polygon(poly, fill=c)
elif t == "window":
d.polygon(poly, fill=(255, 255, 255), outline=c, width=2)
elif t == "column":
d.polygon(poly, fill=_mix(c, 0.35), outline=c, width=2)
d.line([poly[0], poly[2]], fill=c, width=1)
d.line([poly[1], poly[3]], fill=c, width=1)
elif t in FILLED:
d.polygon(poly, fill=_mix(c, 0.85), outline=_rgb(_shade(_color(item))), width=2)
text = _text(item)
if text:
size = max(8, h * 0.6) if t == "label" else max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60))
# bei 90°/270° steht der Text quer – dann an der Höhe statt der Breite ausrichten
vertical = 45 < (item.rotation or 0) % 180 < 135
if vertical and t != "label":
size = max(6, min(w * 0.3, (h * 1.6) / max(len(text), 3), 60))
fill = (255, 255, 255) if t in FILLED else c if t == "label" else _rgb(_shade(_color(item)))
font = _font(max(8, round(size * s)))
if t == "area":
d.text(rot(x + size * 0.5, y + size * 1.2), text, fill=fill, font=font, anchor="lm")
else:
d.text(pt(cx, cy), text, fill=fill, font=font, anchor="mm")
d.rectangle([pt(0, 0), pt(width, depth)], outline=_rgb(WALL), width=3)
font = _font(max(10, round(fs * s)))
d.text(pt(width / 2, -fs * 0.6), f"{meters(width)} m", fill=_rgb(MUTED), font=font, anchor="ms")
label = Image.new("RGBA", (round(fs * s * 8), round(fs * s * 1.6)), (255, 255, 255, 0))
ImageDraw.Draw(label).text((label.width / 2, label.height / 2), f"{meters(depth)} m", fill=_rgb(MUTED), font=font, anchor="mm")
label = label.rotate(90, expand=True)
lx, ly = pt(-fs * 0.6, depth / 2)
img.paste(label, (round(lx - label.width * 0.7), round(ly - label.height / 2)), label)
out = BytesIO()
img.save(out, "PNG", optimize=True)
return out.getvalue()
# --- Abschnitt ----------------------------------------------------------------
def floorplan_blocks(scope, opts):
blocks = []
for plan in floorplans(scope):
items = _items(plan)
where = " / ".join(str(x) for x in (plan.site, plan.location) if x)
blocks.append(H(2, f"{plan.name} ({where})" if where else plan.name))
blocks.append(
KV(
[
(_("Site"), plan.site),
(_("Location"), plan.location),
(_("Tenant"), plan.tenant),
(_("Room size"), f"{meters(plan.width)} × {meters(plan.depth)} m"),
(_("Description"), plan.description),
]
)
)
svg, png, error = None, None, None
try:
svg = render_svg(plan, items)
except Exception as e: # noqa: BLE001
error = f"{type(e).__name__}: {e}"
if opts.get("format") == "docx" or not svg:
try:
png = render_png(plan, items)
except Exception as e: # noqa: BLE001
error = f"{error or ''} / PNG: {type(e).__name__}: {e}".strip(" /")
if svg or png:
blocks.append(IMAGES([(svg, "", png)], wide=True))
else:
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 _("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"), _("Type"), _("Label in plan")], rows))
if plan.comments:
blocks.append(P(plan.comments))
return blocks
+13 -1
View File
@@ -67,6 +67,7 @@ class ExportForm(forms.Form):
)
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", _("Model")), ("primary_ip", _("Management IP")), ("ports", _("Ports on links"))),
@@ -76,7 +77,12 @@ class ExportForm(forms.Form):
label=_("Labels"),
)
topo_scope = forms.MultipleChoiceField(
choices=(("site", _("Whole network (per site)")), ("rack", _("Per rack"))),
choices=(
("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,
@@ -109,6 +115,12 @@ class ExportForm(forms.Form):
elif isinstance(field.widget, forms.TextInput):
field.widget.attrs["class"] = "form-control"
self.fields["branding"].choices = [(k, b["name"]) for k, b in get_brandings().items()]
self.photo_groups = []
if scope is not None:
from .rack_photos import grouped
self.photo_groups = grouped(scope)
self.fields["rack_photos"].choices = [(str(a.pk), a.name) for _r, atts in self.photo_groups for a in atts]
if scope is not None:
role_ids = scope.devices().values("role")
roles = DeviceRole.objects.filter(pk__in=role_ids).order_by("name")
@@ -0,0 +1,51 @@
"""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():
if not apps.is_installed("netbox_utilities"):
return False
try:
apps.get_model("netbox_utilities", "DeviceHardware")
except LookupError: # ältere Version ohne CPU & RAM
return False
return True
def hardware(device):
"""DeviceHardware des Geräts oder None (nicht installiert / nicht gepflegt)."""
if not is_installed():
return None
return getattr(device, "netbox_utilities_hardware", None) # RelatedObjectDoesNotExist ist ein AttributeError
def cores_threads(hw):
"""(Kerne, Threads) gesamt oder (None, None)."""
if not hw or not hw.cpu_id:
return None, None
return hw.total_cores, hw.total_threads
def format_memory(gigabytes):
from netbox_utilities import hardware as helpers
return helpers.format_memory(gigabytes)
def cpu_text(device):
"""„2 × Intel Xeon Gold 6130“ + Zeile „32 Kerne / 64 Threads“."""
hw = hardware(device)
if not hw or not hw.cpu_id:
return None
cores, threads = cores_threads(hw)
return f"{hw.cpu_display}\n" + _("%(cores)s cores / %(threads)s threads") % {"cores": cores, "threads": threads}
def ram_text(device):
"""„384 GB“ + Zeile „12 × 32 GB · DDR4-2666“."""
hw = hardware(device)
if not hw or not hw.memory_gb:
return None
detail = hw.memory_detail
return f"{format_memory(hw.memory_gb)}\n{detail}" if detail else format_memory(hw.memory_gb)
@@ -73,7 +73,9 @@ msgstr "Anschrift"
msgid ""
"1 Sample Street\n"
"Sample City"
msgstr "Musterstraße 1\n12345 Musterstadt"
msgstr ""
"Musterstraße 1\n"
"12345 Musterstadt"
#: branding_views.py:77 sections.py:104 sections.py:235 sections.py:237
#: templates/netbox_customer_export/export.html:100
@@ -339,12 +341,16 @@ msgstr "PNG oder JPG, erscheint auf dem Deckblatt."
#: forms.py:150
msgid ".docx or .dotx: styles, header/footer and margins are applied."
msgstr ".docx oder .dotx: Formatvorlagen, Kopf-/Fußzeile und Ränder werden übernommen."
msgstr ""
".docx oder .dotx: Formatvorlagen, Kopf-/Fußzeile und Ränder werden "
"übernommen."
#: forms.py:151
msgid ""
"Name as shown in Word, e.g. Grid Table 4 – Accent 1. Empty = own colouring."
msgstr "Name wie in Word angezeigt, z.B. Gitternetztabelle 4 – Akzent 1. Leer = eigene Einfärbung."
msgstr ""
"Name wie in Word angezeigt, z.B. Gitternetztabelle 4 – Akzent 1. Leer = "
"eigene Einfärbung."
#: forms.py:165 models.py:84 models.py:106
msgid "Device type"
@@ -368,7 +374,9 @@ msgstr "Symbol"
msgid ""
"PNG, JPG or GIF, ideally square with a transparent background. Replaces the "
"selected symbol."
msgstr "PNG, JPG oder GIF, am besten quadratisch mit transparentem Hintergrund. Ersetzt das gewählte Symbol."
msgstr ""
"PNG, JPG oder GIF, am besten quadratisch mit transparentem Hintergrund. "
"Ersetzt das gewählte Symbol."
#: licenses_slm.py:61
msgid "unlimited"
@@ -578,14 +586,17 @@ msgstr "Branding-Profile"
#, python-format
msgid ""
"PDF export requires WeasyPrint (pip install weasyprint + Pango): %(error)s"
msgstr "PDF-Export benötigt WeasyPrint (pip install weasyprint + Pango): %(error)s"
msgstr ""
"PDF-Export benötigt WeasyPrint (pip install weasyprint + Pango): %(error)s"
#: renderers/docx.py:51
#, python-format
msgid ""
"Word export requires python-docx (pip install python-docx cairosvg): "
"%(error)s"
msgstr "Word-Export benötigt python-docx (pip install python-docx cairosvg): %(error)s"
msgstr ""
"Word-Export benötigt python-docx (pip install python-docx cairosvg): "
"%(error)s"
#: renderers/docx.py:61
#, python-format
@@ -784,7 +795,9 @@ msgstr "Aus Netbox-Utilities (falls installiert)"
#: sections.py:264
msgid "Netbox-Utilities with disk management is not installed – see README."
msgstr "Netbox-Utilities mit Datenträger-Verwaltung ist nicht installiert – siehe README."
msgstr ""
"Netbox-Utilities mit Datenträger-Verwaltung ist nicht installiert – siehe "
"README."
#: sections.py:269 sections.py:272
msgid "Power"
@@ -946,7 +959,9 @@ msgstr "Aus NetBox-SLM oder anderem Lizenz-Plugin"
#: sections.py:444
msgid ""
"No license plugin installed (NetBox-SLM or netbox-lifecycle) – see README."
msgstr "Kein Lizenz-Plugin installiert (NetBox-SLM oder netbox-lifecycle) – siehe README."
msgstr ""
"Kein Lizenz-Plugin installiert (NetBox-SLM oder netbox-lifecycle) – siehe "
"README."
#: sections.py:448 sections.py:452
msgid "Network topology"
@@ -973,7 +988,9 @@ msgstr "Topologie-Symbol für „%(name)s“ gespeichert."
#, python-format
msgid ""
"Topology symbol for “%(name)s” deleted – automatic detection applies again."
msgstr "Topologie-Symbol für „%(name)s“ gelöscht – es gilt wieder die automatische Erkennung."
msgstr ""
"Topologie-Symbol für „%(name)s“ gelöscht – es gilt wieder die automatische "
"Erkennung."
#: symbols.py:12
msgid "Internet / provider"
@@ -1099,9 +1116,12 @@ msgstr "%(object)s löschen"
#: templates/netbox_customer_export/branding_delete.html:9
#, python-format
msgid ""
"Do you really want to delete the branding profile <strong>%(object)s</"
"strong>? The profile's logo and Word template will be removed as well."
msgstr "Soll das Branding-Profil <strong>%(object)s</strong> wirklich gelöscht werden? Logo und Word-Vorlage des Profils werden ebenfalls entfernt."
"Do you really want to delete the branding profile "
"<strong>%(object)s</strong>? The profile's logo and Word template will be "
"removed as well."
msgstr ""
"Soll das Branding-Profil <strong>%(object)s</strong> wirklich gelöscht "
"werden? Logo und Word-Vorlage des Profils werden ebenfalls entfernt."
#: templates/netbox_customer_export/branding_delete.html:13
#: templates/netbox_customer_export/branding_edit.html:77
@@ -1162,7 +1182,9 @@ msgstr "Akzent"
msgid ""
"No branding profiles yet. Until then, the settings from "
"<code>configuration.py</code> apply."
msgstr "Noch keine Branding-Profile angelegt. Bis dahin gelten die Einstellungen aus <code>configuration.py</code>."
msgstr ""
"Noch keine Branding-Profile angelegt. Bis dahin gelten die Einstellungen aus"
" <code>configuration.py</code>."
#: templates/netbox_customer_export/document.html:10
msgid "Page"
@@ -1184,7 +1206,8 @@ msgstr "Leer = dein Benutzername"
#: templates/netbox_customer_export/export.html:62
msgid ""
"Applies to management/OOB IPs, VMs, topology, IP networks and IP addresses."
msgstr "Gilt für Management-/OOB-IPs, VMs, Topologie, IP-Netze und IP-Adressen."
msgstr ""
"Gilt für Management-/OOB-IPs, VMs, Topologie, IP-Netze und IP-Adressen."
#: templates/netbox_customer_export/export.html:64
msgid "Options"
@@ -1229,7 +1252,9 @@ msgstr "Symbole verwalten"
msgid ""
"“Per rack” additionally shows each rack separately; connected devices "
"outside appear dashed."
msgstr "„Je Rack“ zeigt zusätzlich jedes Rack einzeln; verbundene Geräte außerhalb erscheinen gestrichelt."
msgstr ""
"„Je Rack“ zeigt zusätzlich jedes Rack einzeln; verbundene Geräte außerhalb "
"erscheinen gestrichelt."
#: templates/netbox_customer_export/export.html:158
msgid "Create document"
@@ -1257,7 +1282,10 @@ msgid ""
"Delete the symbol assignment for <strong>%(label)s %(object)s</strong>? "
"Automatic detection applies again afterwards. An uploaded icon will be "
"removed as well."
msgstr "Soll die Symbol-Zuordnung für <strong>%(label)s %(object)s</strong> gelöscht werden? Danach gilt wieder die automatische Erkennung. Ein hochgeladenes Icon wird ebenfalls entfernt."
msgstr ""
"Soll die Symbol-Zuordnung für <strong>%(label)s %(object)s</strong> gelöscht"
" werden? Danach gilt wieder die automatische Erkennung. Ein hochgeladenes "
"Icon wird ebenfalls entfernt."
#: templates/netbox_customer_export/symbol_edit.html:4
#, python-format
@@ -1274,9 +1302,11 @@ msgstr "Gilt für"
#: templates/netbox_customer_export/symbol_edit.html:25
msgid ""
"Select either a device type <em>or</em> a device role. The device type takes "
"precedence."
msgstr "Entweder einen Gerätetyp <em>oder</em> eine Geräterolle wählen. Gerätetyp hat Vorrang."
"Select either a device type <em>or</em> a device role. The device type takes"
" precedence."
msgstr ""
"Entweder einen Gerätetyp <em>oder</em> eine Geräterolle wählen. Gerätetyp "
"hat Vorrang."
#: templates/netbox_customer_export/symbol_edit.html:48
msgid "Custom icon (optional)"
@@ -1290,7 +1320,8 @@ msgstr "Aktuelles Icon"
msgid ""
"If no symbol is selected, automatic detection determines the level in the "
"diagram."
msgstr "Ist kein Symbol gewählt, bestimmt die Automatik die Ebene im Diagramm."
msgstr ""
"Ist kein Symbol gewählt, bestimmt die Automatik die Ebene im Diagramm."
#: templates/netbox_customer_export/symbol_list.html:7
msgid "Add assignment"
@@ -1329,7 +1360,10 @@ msgid ""
"<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."
msgstr "<strong>Automatisch</strong> anhand von Rolle, Modell und Hersteller, z.B. „Switch“, „Firewall“, „Sophos“, „Access Point“. Patchpanels, Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet."
msgstr ""
"<strong>Automatisch</strong> anhand von Rolle, Modell und Hersteller, z.B. "
"„Switch“, „Firewall“, „Sophos“, „Access Point“. Patchpanels, "
"Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet."
#: templates/netbox_customer_export/symbol_list.html:44
msgid "Built-in symbols"
@@ -1339,3 +1373,171 @@ msgstr "Eingebaute Symbole"
#, python-format
msgid "Rack %(name)s (%(where)s)"
msgstr "Rack %(name)s (%(where)s)"
msgid "%(cores)s cores / %(threads)s threads"
msgstr "%(cores)s Kerne / %(threads)s Threads"
msgid "Appendix rack photos – rack %(name)s"
msgstr "Anhang Rack-Fotos – Rack %(name)s"
msgid "Appendix: rack photos"
msgstr "Anhang: Rack-Fotos"
msgid "Back to rack elevation"
msgstr "Zurück zur Rack-Ansicht"
msgid "CPU"
msgstr "CPU"
msgid "Cable"
msgstr "Kabel"
msgid "Cluster %(name)s"
msgstr "Cluster %(name)s"
msgid "Cores / threads (hosts)"
msgstr "Kerne / Threads (Hosts)"
msgid "Disk"
msgstr "Datenträger"
msgid "Floor plan could not be generated: %(error)s"
msgstr "Raumplan konnte nicht erzeugt werden: %(error)s"
msgid "Floor plans"
msgstr "Raumpläne"
msgid "From NetBox-FloorPlan (if installed)"
msgstr "Aus NetBox-FloorPlan (falls installiert)"
msgid "Host"
msgstr "Host"
msgid "Hosts"
msgstr "Hosts"
msgid "Hosts and resources per cluster"
msgstr "Hosts und Ressourcen je Cluster"
msgid "Label in plan"
msgstr "Beschriftung im Plan"
msgid "Location / distribution"
msgstr "Lokation / Verteiler"
msgid "Location overview"
msgstr "Lokationsübersicht"
msgid "Location overview (connections between locations)"
msgstr "Lokationsübersicht (Verbindungen zwischen Lokationen)"
msgid "No disks recorded."
msgstr "Keine Datenträger erfasst."
msgid "No floor plans recorded."
msgstr "Keine Raumpläne erfasst."
msgid ""
"No image attachments found on racks in this scope. Photos can be uploaded on"
" the rack via <em>Attach an image</em>."
msgstr ""
"Keine Bildanhänge an Racks in diesem Scope gefunden. Fotos lassen sich am "
"Rack über <em>Bild anhängen</em> hochladen."
msgid "Patch panel / distribution frame"
msgstr "Patchfeld / Rangierverteiler"
msgid "RAM"
msgstr "RAM"
msgid "RAM (hosts)"
msgstr "RAM (Hosts)"
msgid "RAM (total of VMs)"
msgstr "RAM (Summe VMs)"
msgid "RAM of VMs"
msgstr "RAM VMs"
msgid "RAM of VMs / hosts"
msgstr "RAM VMs / Hosts"
msgid "Rack photos"
msgstr "Rack-Fotos"
msgid "Room size"
msgstr "Raumgröße"
msgid ""
"Selected photos appear in the appendix at the end of the document; a link to"
" them is placed below the rack elevation."
msgstr ""
"Ausgewählte Fotos erscheinen im Anhang am Dokumentende, unter der jeweiligen"
" Rack-Ansicht steht ein Verweis darauf."
msgid "Storage"
msgstr "Speicher"
msgid "Storage (total)"
msgstr "Speicher (Summe)"
msgid "VMs"
msgstr "VMs"
msgid "VMs active / total"
msgstr "VMs aktiv / gesamt"
msgid "VMs without a fixed host are only included in the cluster totals."
msgstr "VMs ohne festen Host sind nur in den Cluster-Summen enthalten."
msgid "Virtualization clusters"
msgstr "Virtualisierungs-Cluster"
msgid "vCPU"
msgstr "vCPU"
msgid "vCPU (total of VMs)"
msgstr "vCPU (Summe VMs)"
msgid "vCPU / cores"
msgstr "vCPU / Kerne"
msgid "vCPU per core"
msgstr "vCPU je Kern"
msgid ""
"“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."
msgstr ""
"„Lokationsübersicht“ zeigt alle Lokationen eines Standorts und die Kabel "
"zwischen ihnen, vom Serverraum bis zur letzten Unterverteilung. "
"„Standortübergreifend“ fasst alle Standorte in einem Diagramm zusammen, um "
"zu sehen, wie Gebäude und ihre Lokationen verbunden sind. „Je Rack“ zeigt "
"jedes Rack einzeln. Verbundene Geräte außerhalb erscheinen gestrichelt."
msgid "%(n)d device"
msgid_plural "%(n)d devices"
msgstr[0] "%(n)d Gerät"
msgstr[1] "%(n)d Geräte"
msgid "%(n)d photo, see "
msgid_plural "%(n)d photos, see "
msgstr[0] "%(n)d Foto, siehe "
msgstr[1] "%(n)d Fotos, siehe "
msgid "%(n)d rack"
msgid_plural "%(n)d racks"
msgstr[0] "%(n)d Rack"
msgstr[1] "%(n)d Racks"
msgid "Cross-site location overview (all locations in one diagram)"
msgstr "Lokationsübersicht standortübergreifend (alle Lokationen in einem Diagramm)"
msgid "Cross-site location overview"
msgstr "Standortübergreifende Lokationsübersicht"
msgid "All sites"
msgstr "Alle Standorte"
+58
View File
@@ -0,0 +1,58 @@
"""Bildanhänge (extras.ImageAttachment) von Racks: Auswahl im Formular und Anhang am Dokumentende."""
from io import BytesIO
from dcim.models import Rack
from django.contrib.contenttypes.models import ContentType
from extras.models import ImageAttachment
MAX_EDGE = 1600 # px – Handyfotos verkleinern, damit PDF/Word handlich bleiben
def attachments(scope):
"""Bildanhänge aller Racks im Scope, die der Benutzer sehen darf – sortiert nach Rack."""
racks = {r.pk: r for r in scope.racks().select_related("site", "location")}
if not racks:
return []
qs = (
ImageAttachment.objects.restrict(scope.user, "view")
.filter(object_type=ContentType.objects.get_for_model(Rack), object_id__in=racks)
.order_by("name", "pk")
)
items = [(racks[a.object_id], a) for a in qs]
items.sort(key=lambda x: (str(x[0].site), str(x[0].location or ""), x[0].name))
return items
def grouped(scope):
"""[(rack, [attachment, …]), …] für die Vorschau im Formular."""
out = []
for rack, att in attachments(scope):
if out and out[-1][0] == rack:
out[-1][1].append(att)
else:
out.append((rack, [att]))
return out
def caption(att):
name = att.name or att.image.name.rsplit("/", 1)[-1]
desc = getattr(att, "description", "")
return f"{name} – {desc}" if desc else name
def load_jpeg(att):
"""Bild drehen (EXIF), verkleinern und als JPEG zurückgeben. None, wenn nicht lesbar."""
from PIL import Image, ImageOps
try:
with att.image.open("rb") as f:
img = Image.open(BytesIO(f.read()))
img = ImageOps.exif_transpose(img)
img.thumbnail((MAX_EDGE, MAX_EDGE))
if img.mode != "RGB":
img = img.convert("RGB")
out = BytesIO()
img.save(out, "JPEG", quality=85)
return out.getvalue()
except Exception: # noqa: BLE001 – fehlende/defekte Datei überspringen
return None
+56 -3
View File
@@ -1,3 +1,4 @@
import re
import zipfile
from io import BytesIO
@@ -20,6 +21,11 @@ def _svg_to_png(svg):
return None
def _bookmark_name(anchor):
"""Word-Textmarken: max. 40 Zeichen, Buchstabe vorne, nur Buchstaben/Ziffern/_."""
return ("_ce_" + re.sub(r"\W", "_", anchor))[:40]
def _load_template(path):
"""Öffnet eine .docx/.dotx-Vorlage und leert deren Textkörper (Formatvorlagen, Kopf-/Fußzeile bleiben)."""
from docx import Document as Docx
@@ -140,6 +146,38 @@ def render_docx(doc):
s.header_distance, s.footer_distance) = portrait_margins
return s
targets = {blk.anchor for blk in doc.blocks if blk.kind == "ref"}
bookmark_id = [0]
def add_bookmark(paragraph, anchor):
bookmark_id[0] += 1
start = OxmlElement("w:bookmarkStart")
start.set(qn("w:id"), str(bookmark_id[0]))
start.set(qn("w:name"), _bookmark_name(anchor))
end = OxmlElement("w:bookmarkEnd")
end.set(qn("w:id"), str(bookmark_id[0]))
paragraph._p.insert(1 if paragraph._p.pPr is not None else 0, start)
paragraph._p.append(end)
def add_link(paragraph, text, anchor):
link = OxmlElement("w:hyperlink")
link.set(qn("w:anchor"), _bookmark_name(anchor))
run = OxmlElement("w:r")
rpr = OxmlElement("w:rPr")
color = OxmlElement("w:color")
color.set(qn("w:val"), b["primary_color"])
underline = OxmlElement("w:u")
underline.set(qn("w:val"), "single")
rpr.append(color)
rpr.append(underline)
run.append(rpr)
t = OxmlElement("w:t")
t.text = text
t.set(qn("xml:space"), "preserve")
run.append(t)
link.append(run)
paragraph._p.append(link)
for blk in doc.blocks:
if landscape_open and blk.kind != "landscape":
# erst beim nächsten Inhalt zurück ins Hochformat – vermeidet leere Seiten
@@ -169,9 +207,18 @@ def render_docx(doc):
else:
para.add_run().add_picture(BytesIO(png), height=avail_h)
elif blk.kind == "heading":
d.add_heading(blk.text, level=min(blk.level, 4))
heading = d.add_heading(blk.text, level=min(blk.level, 4))
if blk.anchor in targets:
add_bookmark(heading, blk.anchor)
elif blk.kind == "paragraph":
d.add_paragraph(blk.text)
elif blk.kind == "ref":
para = d.add_paragraph()
if blk.rows and blk.rows[0]:
para.add_run(blk.rows[0])
add_link(para, blk.text, blk.anchor)
for r in para.runs:
r.font.size = Pt(max(b["font_size"] - 1, 7))
elif blk.kind == "pagebreak":
d.add_page_break()
elif blk.kind in ("table", "kv"):
@@ -211,8 +258,14 @@ def render_docx(doc):
cell = t.cell(0, i).paragraphs[0]
cell.alignment = WD_ALIGN_PARAGRAPH.CENTER
if png:
# Topologie: volle Breite; Racks: 7 cm (Höhe skaliert mit der Rackgröße)
cell.add_run().add_picture(BytesIO(png), width=Cm(16.5 if blk.level == 1 else 7))
# Topologie: volle Breite; Fotos: halbe Breite; Racks: 7 cm (Höhe skaliert mit der Rackgröße)
width = {1: 16.5, 2: 8}.get(blk.level, 7)
if blk.level == 2:
from PIL import Image
px_w, px_h = Image.open(BytesIO(png)).size
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 graphic not available)"))
cap = t.cell(1, i).paragraphs[0]
+7 -1
View File
@@ -6,7 +6,7 @@ from circuits.models import Circuit
from dcim.models import Device, Location, PowerFeed, Rack, Site
from ipam.models import VLAN, VRF, IPAddress, Prefix
from tenancy.models import Tenant, TenantGroup
from virtualization.models import VirtualMachine
from virtualization.models import Cluster, VirtualMachine
from wireless.models import WirelessLAN
SCOPE_MODELS = {
@@ -82,6 +82,12 @@ class Scope:
def devices(self):
return self._qs(Device, site=("site",), location=("location",))
def clusters(self):
"""Cluster am Scope selbst oder mit Hosts/VMs im Scope."""
own = Cluster.objects.filter(self._q(site=("_site",), location=("_location",), tenant=("tenant",)))
q = Q(pk__in=own.values("pk")) | Q(pk__in=self.devices().values("cluster")) | Q(pk__in=self.virtual_machines().values("cluster"))
return self.restrict(Cluster.objects.filter(q).distinct())
def virtual_machines(self):
return self._qs(
VirtualMachine,
+172 -7
View File
@@ -6,10 +6,11 @@ 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
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, T, get
from .blocks import EMPTY, H, IMAGES, KV, LANDSCAPE, P, PAGEBREAK, REF, T, get
from . import hardware_utilities
from .rack_png import render_rack_png
from .rack_svg import render_rack_svg
@@ -54,10 +55,20 @@ def primary_ips(obj, opts, sep=", "):
return ip_text([obj.primary_ip4, obj.primary_ip6], opts, sep)
def num(value):
"""Decimal/float ohne überflüssige Nachkommastellen, deutsches Komma: 245, 2,5."""
if value is None:
return None
text = f"{value:f}"
if "." in text:
text = text.rstrip("0").rstrip(".")
return text.replace(".", ",")
def _rack_pos(d, o=None):
if not d.rack:
return None
pos = " / " + _("U %(u)s") % {"u": f"{d.position:g}"} if d.position else ""
pos = " / " + _("U %(u)s") % {"u": num(d.position)} if d.position else ""
return f"{d.rack}{pos}"
@@ -73,6 +84,8 @@ DEVICE_COLUMNS = OrderedDict(
("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)),
@@ -173,12 +186,14 @@ def racks(scope, opts):
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, _("Site %(name)s") % {"name": site}))
for location, loc_racks in groupby(site_racks, key=lambda r: r.location):
blocks.append(H(3, _("Location %(name)s") % {"name": location} if location else _("No location")))
for rack in loc_racks:
blocks.append(H(4, _("Rack %(name)s") % {"name": rack.name}))
rack_heading = H(4, _("Rack %(name)s") % {"name": rack.name})
blocks.append(rack_heading)
blocks.append(
KV(
[
@@ -222,16 +237,56 @@ def racks(scope, opts):
T(
[_("U"), _("Device"), _("Manufacturer / model"), _("Face")],
[
[f"{d.position:g}" 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]
[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
],
)
)
if rack.pk in photos:
blocks += _photo_appendix(opts, rack, rack_heading, photos[rack.pk])
if opts.get("rack_pagebreak"):
blocks.append(PAGEBREAK())
return blocks
def _rack_photos(scope, opts):
"""Ausgewählte Bildanhänge je Rack-ID."""
selected = set(opts.get("rack_photos") or [])
if not selected:
return {}
from . import rack_photos
out = {}
for rack, att in rack_photos.attachments(scope):
if str(att.pk) in selected:
out.setdefault(rack.pk, []).append(att)
return out
def _photo_appendix(opts, rack, rack_heading, atts):
"""Legt die Fotos im Anhang ab (opts["_appendix"]) und liefert den Verweis unter der Rack-Ansicht."""
from . import rack_photos
images = [(None, rack_photos.caption(a), data) for a in atts if (data := rack_photos.load_jpeg(a))]
if not images:
return []
appendix = opts.setdefault("_appendix", [])
if not appendix:
appendix.append(H(1, _("Appendix: rack photos")))
where = " / ".join(str(x) for x in (rack.site, rack.location) if x)
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(_("Back to rack elevation"), rack_heading.anchor, prefix="↑ "))
n = len(images)
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", gettext_lazy("Devices"), gettext_lazy("Infrastructure"), hint=gettext_lazy("Tables per device role"))
def devices(scope, opts):
blocks = [H(1, _("Devices"))]
@@ -261,11 +316,22 @@ def disks(scope, opts):
blocks = [H(1, _("Disks & RAID"))]
if not disks_utilities.is_installed():
return _empty(opts, blocks, _("Netbox-Utilities with disk management is not installed – see README."))
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", 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, _("Floor plans"))]
if not floorplan.is_installed():
return _empty(opts, blocks, _("No floor plans recorded."))
blocks += floorplan.floorplan_blocks(scope, opts)
return blocks if len(blocks) > 1 else _empty(opts, blocks, _("No floor plans recorded."))
@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")
@@ -281,6 +347,100 @@ def power(scope, opts):
return blocks
def _mb(value):
"""MB als lesbare Größe (VM-RAM/-Disk sind in NetBox in MB gespeichert)."""
if not value:
return EMPTY
for unit, size in (("TB", 1024 ** 2), ("GB", 1024)):
if value >= size:
return f"{value / size:.1f} {unit}".replace(".0 ", " ").replace(".", ",")
return f"{value} MB"
def _host_resources(hosts):
"""Summe der physischen Kerne, Threads und RAM (GB) aller Hosts mit gepflegter Hardware."""
cores = threads = ram = 0
for host in hosts:
hw = hardware_utilities.hardware(host)
c, t = hardware_utilities.cores_threads(hw)
cores, threads = cores + (c or 0), threads + (t or 0)
ram += (hw.memory_gb or 0) if hw else 0
return cores, threads, ram
def _vm_totals(vms):
return (
sum(vm.vcpus or 0 for vm in vms),
sum(vm.memory or 0 for vm in vms),
sum(vm.disk or 0 for vm in vms),
)
@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, _("Virtualization clusters"))]
if not qs.exists():
return _empty(opts, blocks)
vms_by_cluster = {}
for vm in scope.virtual_machines().select_related("device"):
vms_by_cluster.setdefault(vm.cluster_id, []).append(vm)
summary, details = [], []
for cluster in qs:
vms = vms_by_cluster.get(cluster.pk, [])
hosts = list(scope.restrict(cluster.devices.all()).select_related("device_type__manufacturer").order_by("name"))
vcpu, ram, disk = _vm_totals(vms)
active = sum(1 for vm in vms if vm.status == "active")
p_cores, p_threads, p_ram = _host_resources(hosts)
ram_pct = f" ({round(ram / (p_ram * 1024) * 100)} %)" if ram and p_ram else ""
summary.append([
cluster.name, cluster.type, len(hosts), f"{active} / {len(vms)}",
f"{num(vcpu)} / {p_cores}" if vcpu and p_cores else num(vcpu) if vcpu else EMPTY,
f"{_mb(ram)} / {hardware_utilities.format_memory(p_ram)}" if ram and p_ram else _mb(ram),
_mb(disk),
])
details.append(H(2, _("Cluster %(name)s") % {"name": cluster.name}))
details.append(KV([
(_("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 = []
for host in hosts:
host_vms = [vm for vm in vms if vm.device_id == host.pk]
h_vcpu, h_ram, _h_disk = _vm_totals(host_vms)
h_cores, _t, h_pram = _host_resources([host])
rows.append([
host.name,
f"{host.device_type.manufacturer} {host.device_type.model}",
hardware_utilities.cpu_text(host),
hardware_utilities.format_memory(h_pram) if h_pram else None,
len(host_vms) if host_vms else EMPTY,
(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"), _("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 without a fixed host are only included in the cluster totals.")))
blocks.append(T([_("Cluster"), _("Type"), _("Hosts"), _("VMs active / total"), _("vCPU / cores"), _("RAM of VMs / hosts"), _("Storage")], summary))
return blocks + details
@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")
@@ -447,7 +607,7 @@ def licenses(scope, opts):
@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, render_png
from .topology import build_graphs, build_location_graphs, render_png
title = H(1, _("Network topology"))
scopes = opts.get("topo_scope") or ["site"]
@@ -455,6 +615,11 @@ def topology(scope, opts):
pages = [] # (Überschriften, Graph) – je eine Querformat-Seite
if "site" in scopes:
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, _("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)
+27 -1
View File
@@ -10,12 +10,14 @@ from django.utils.translation import gettext_lazy as _
KINDS = OrderedDict(
[
("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)),
@@ -33,7 +35,7 @@ KINDS = OrderedDict(
]
)
HIDDEN = "hidden"
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k != "cloud"] + [(HIDDEN, _("Hide in topology"))]
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.
@@ -288,6 +290,23 @@ def _draw_ups(d):
d.polygon([(62, 70), (50, 88), (58, 88), (54, 102), (70, 82), (62, 82), (68, 70)], fill=(250, 200, 40))
def _draw_patchpanel(d):
# flaches 19"-Feld mit zwei Portreihen, bewusst nüchtern (passives Element)
_iso_box(d, 8, 58, 104, 92, 14, (96, 104, 114), (150, 158, 168), (74, 82, 92))
for row in (64, 78):
for i in range(12):
d.rectangle([14 + i * 7.5, row, 19 + i * 7.5, row + 7], fill=(40, 46, 54))
def _draw_location(d):
# Verteilerschrank mit Glastür und Höheneinheiten – steht in der Übersicht für eine ganze Lokation
_iso_box(d, 26, 20, 92, 116, 12, (58, 74, 92), (118, 136, 156), (42, 56, 72))
d.rectangle([33, 27, 85, 109], fill=(170, 196, 220), outline=OUTLINE, width=2)
for i, y in enumerate(range(33, 101, 11)):
d.rectangle([38, y, 80, y + 7], fill=(40, 52, 66))
d.ellipse([74, y + 2, 77, y + 5], fill=(60, 200, 90) if i % 2 == 0 else (86, 149, 206))
def _draw_pbx(d):
# Anlage (Box) mit Hörer-Symbol
_iso_box(d, 12, 50, 104, 104, 12, (62, 70, 80), (126, 136, 148), (44, 52, 60))
@@ -321,6 +340,8 @@ _DRAWERS = {
"tape": _draw_tape,
"ups": _draw_ups,
"pbx": _draw_pbx,
"patchpanel": _draw_patchpanel,
"location": _draw_location,
}
@@ -368,6 +389,11 @@ class SymbolResolver:
pass
self._icons = {}
def is_hidden(self, device):
"""Per Symbolzuordnung ausdrücklich ausgeblendet?"""
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
return bool(sym and sym.kind == HIDDEN)
def resolve(self, device):
"""(kind, icon_png_bytes) oder (None, None), wenn das Gerät nicht gezeichnet wird."""
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
@@ -29,6 +29,7 @@
table { width: 100%; border-collapse: collapse; margin: 4pt 0 10pt; font-size: 8.5pt; }
thead { display: table-header-group; }
th { background: var(--primary); color: var(--head-text); text-align: left; padding: 3pt 5pt; }
th, td { overflow-wrap: anywhere; }
td { border-bottom: 1px solid #ddd; padding: 3pt 5pt; vertical-align: top; }
tr { page-break-inside: avoid; }
tbody tr:nth-child(even) td { background: var(--stripe); }
@@ -39,6 +40,11 @@
.images img { max-height: 190mm; max-width: 80mm; }
.images.wide figure { width: 100%; min-width: 0; }
.images.wide img { width: 100%; height: auto; max-height: 240mm; object-fit: contain; }
.images.photos { display: flex; gap: 6mm; justify-content: flex-start; page-break-inside: avoid; }
.images.photos figure { width: calc(50% - 3mm); margin: 0 0 6mm; }
.images.photos img { width: 100%; height: auto; max-width: none; max-height: 95mm; object-fit: contain; border: 1px solid #ddd; }
.ref { font-size: 8.5pt; color: #555; margin: 2pt 0 8pt; }
.ref a { color: var(--primary); text-decoration: none; border-bottom: 1px solid currentColor; }
figcaption { font-style: italic; color: #555; }
.footer { position: running(footer); font-size: 7pt; color: #777; }
@media screen { .footer { display: none; } }
@@ -73,13 +79,14 @@
{% if b.kind == 'heading' %}
{% if b.level == 1 %}<h1 id="{{ b.anchor }}">{{ b.text }}</h1>{% elif b.level == 2 %}<h2 id="{{ b.anchor }}">{{ b.text }}</h2>{% elif b.level == 3 %}<h3 id="{{ b.anchor }}">{{ b.text }}</h3>{% else %}<h4 id="{{ b.anchor }}">{{ b.text }}</h4>{% endif %}
{% elif b.kind == 'paragraph' %}<p>{{ b.text|linebreaksbr }}</p>
{% elif b.kind == 'ref' %}<p class="ref">{{ b.rows.0 }}<a href="#{{ b.anchor }}">{{ b.text }}</a></p>
{% elif b.kind == 'table' %}
<table><thead><tr>{% for h in b.headers %}<th>{{ h }}</th>{% endfor %}</tr></thead>
<tbody>{% for row in b.rows %}<tr>{% for c in row %}<td>{{ c|linebreaksbr }}</td>{% endfor %}</tr>{% endfor %}</tbody></table>
{% elif b.kind == 'kv' %}
<table class="kv"><tbody>{% for row in b.rows %}<tr><td>{{ row.0 }}</td><td>{{ row.1|linebreaksbr }}</td></tr>{% endfor %}</tbody></table>
{% elif b.kind == 'images' %}
<div class="images{% if b.level == 1 %} wide{% endif %}">{% for img in b.images %}<figure><img src="{{ img.data_uri }}" alt="{{ img.caption }}">{% if img.caption %}<figcaption>{{ img.caption }}</figcaption>{% endif %}</figure>{% endfor %}</div>
<div class="images{% if b.level == 1 %} wide{% elif b.level == 2 %} photos{% endif %}">{% for img in b.images %}<figure><img src="{{ img.data_uri }}" alt="{{ img.caption }}">{% if img.caption %}<figcaption>{{ img.caption }}</figcaption>{% endif %}</figure>{% endfor %}</div>
{% elif b.kind == 'pagebreak' %}<div class="pagebreak"></div>
{% elif b.kind == 'landscape' %}
<section class="landscape">
@@ -26,6 +26,13 @@
.ce-card { transition: opacity .15s; }
.ce-actions { position: sticky; bottom: 0; z-index: 10; background: var(--tblr-bg-surface); border-top: 1px solid var(--tblr-border-color); padding: .75rem 1rem; display: flex; justify-content: flex-end; gap: .5rem; }
.ce-format .btn { flex: 1; padding-left: .25rem; padding-right: .25rem; }
.ce-photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: .5rem; }
.ce-photo { position: relative; margin: 0; border: 1px solid var(--tblr-border-color); border-radius: .375rem; overflow: hidden; cursor: pointer; background: var(--tblr-bg-surface-secondary); }
.ce-photo:has(input:checked) { border-color: var(--tblr-primary); box-shadow: 0 0 0 1px var(--tblr-primary); }
.ce-photo img { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; }
.ce-photo .form-check-input { position: absolute; top: .4rem; left: .4rem; margin: 0; }
.ce-photo span { display: block; padding: .25rem .4rem; font-size: .75rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.ce-photo-rack + .ce-photo-rack { margin-top: .9rem; }
</style>
<form method="post" class="mt-3" id="ce-export-form">
@@ -132,6 +139,33 @@
</div>
</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> {% trans "Rack photos" %}</h2>
<div class="card-body">
{% if not rack_photos %}
<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">{% 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>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span>
</div>
<div class="ce-photos">
{% for a in atts %}
<label class="ce-photo" title="{{ a.name|default:a.image.name }}">
<input type="checkbox" class="form-check-input" name="rack_photos" value="{{ a.pk }}"{% if a.pk|stringformat:"s" in form.rack_photos.value %} checked{% endif %}>
<img src="{{ a.image.url }}" alt="" loading="lazy">
<span>{{ a.name|default:a.image.name }}</span>
</label>
{% endfor %}
</div>
</div>
{% endfor %}
{% endif %}
</div>
</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> {% trans "Topology" %}</span>
@@ -142,7 +176,7 @@
<div class="card-body">
<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">{% trans "“Per rack” additionally shows each rack separately; connected devices outside appear dashed." %}</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">{% trans "More" %}</div>
+130 -1
View File
@@ -5,6 +5,7 @@ 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
@@ -19,6 +20,7 @@ class Node:
icon: bytes
sub: list = field(default_factory=list)
external: bool = False # Gerät eines anderen Standorts / Provider
tier: int = None # Ebene überschreiben (sonst aus dem Symbol)
row: int = 0 # Zeile im Diagramm (nach Umbruch)
x: float = 0 # Mitte, in Layout-Pixeln
y: float = 0 # Oberkante des Symbols, wird beim Zeichnen gesetzt
@@ -29,6 +31,7 @@ class Edge:
a: str
b: str
labels: list = field(default_factory=list)
summary: str = "" # feste Beschriftung statt Port-Namen (z.B. Lokationsübersicht)
@dataclass
@@ -208,6 +211,130 @@ def _collect(scope, opts):
return by_pk, drawn, links, external
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
resolver = SymbolResolver()
devices = list(
scope.devices().filter(location__isnull=False)
.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}
# 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
if d.rack_id:
racks[d.location_id].add(d.rack_id)
cables = {} # cable.pk -> (Knoten a, Knoten b, Kabel)
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")
for port in ports:
if port.cable_id in cables:
continue
try:
peers = port.link_peers or []
except Exception: # noqa: BLE001
continue
a = f"l{loc_of[port.device_id].pk}"
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}"
elif not opts.get("topo_external"):
continue
else:
loc = getattr(peer_dev, "location", None)
b = f"l{loc.pk}" if loc else f"s{peer_dev.site_id}"
outside[b] = Node(
b, str(loc or peer_dev.site), "location", builtin_icon("location"),
[str(peer_dev.site)], external=True,
)
elif peer._meta.model_name == "circuittermination" and opts.get("topo_external"):
circuit = peer.circuit
b = f"c{circuit.pk}"
outside[b] = Node(b, str(circuit.provider), "cloud", builtin_icon("cloud"), [str(circuit.cid)], external=True)
else:
continue
if a != b:
cables[port.cable_id] = (a, b, port.cable)
break
links = defaultdict(list)
for a, b, cable in cables.values():
links[tuple(sorted((a, b)))].append(cable)
sites = OrderedDict()
all_locs = {}
for d in devices:
sites.setdefault(None if combined else d.site, OrderedDict())[d.location_id] = d.location
all_locs[f"l{d.location_id}"] = d.location
graphs = []
for site, locations in sites.items():
nodes = OrderedDict()
for loc in locations.values():
where = [str(loc.site)] if combined else []
if loc.parent_id:
where.append(str(loc.parent))
sub = [" / ".join(where)] if where else []
n_racks, n_dev = len(racks[loc.pk]), count[loc.pk]
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])
members = set(nodes)
edges = []
for (a, b), lst in links.items():
if not (a in members or b in members):
continue
for nid in (a, b):
if nid in members:
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)
nodes[nid] = Node(**{**tpl.__dict__})
edges.append(Edge(a, b, [str(c) for c in lst], summary=_cable_summary(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)
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“."""
types = defaultdict(int)
for c in cables:
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]))
# --- Layout -------------------------------------------------------------------
CELL_W = 174 # Spaltenbreite (enger = Symbole und Schrift im Dokument größer)
@@ -234,7 +361,7 @@ def _layout(nodes, edges):
for e in edges:
adj[e.a].add(e.b)
adj[e.b].add(e.a)
tier = {nid: KINDS.get(n.kind, ("", 4))[1] for nid, n in nodes.items()}
tier = {nid: n.tier if n.tier is not None else KINDS.get(n.kind, ("", 4))[1] for nid, n in nodes.items()}
layer = {n: None for n in nodes if not adj[n]} # isolierte Knoten: unterste Zeile
remaining = set(nodes) - set(layer)
@@ -303,6 +430,8 @@ def _oriented(graph, e):
def _edge_text(graph, e, show_ports):
if e.summary:
return e.summary
if show_ports:
labels = _oriented(graph, e)
return labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
+4 -1
View File
@@ -42,7 +42,9 @@ class ExportView(LoginRequiredMixin, View):
grouped = {}
for s in SECTIONS.values():
grouped.setdefault(s.group, []).append(s)
return render(request, self.template_name, {"object": scope.obj, "scope": scope, "form": form, "section_groups": grouped})
return render(request, self.template_name, {
"object": scope.obj, "scope": scope, "form": form, "section_groups": grouped, "rack_photos": form.photo_groups,
})
def get(self, request, kind, pk):
scope = self._scope(request, kind, pk)
@@ -58,6 +60,7 @@ class ExportView(LoginRequiredMixin, View):
blocks = []
for key in opts["sections"]:
blocks += SECTIONS[key].func(scope, opts)
blocks += opts.pop("_appendix", []) # z.B. Rack-Fotos, immer am Dokumentende
doc = Document(
title=opts["title"],
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "netbox-customer-export"
version = "0.11.0"
version = "0.18.0"
description = "NetBox plugin: customer documentation (PDF/Word) for sites, locations, tenants and tenant groups"
readme = "README.md"
requires-python = ">=3.10"