Compare commits
9
Commits
feat/i18n
...
4405a65653
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4405a65653 | ||
|
|
ca29980aa6 | ||
|
|
55c70814c3 | ||
|
|
4ec96bf65d | ||
|
|
59ffd2a4b5 | ||
|
|
cd4357f417 | ||
|
|
c888a65180 | ||
|
|
74dfa0ec61 | ||
|
|
2c0e026cb9 |
No files matched your search
@@ -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`) |
|
||||
|
||||
@@ -255,7 +255,8 @@ 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.
|
||||
- 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.
|
||||
@@ -269,7 +270,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".
|
||||
|
||||
@@ -304,6 +305,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
|
||||
|
||||
@@ -5,7 +5,7 @@ class CustomerExportConfig(PluginConfig):
|
||||
name = "netbox_customer_export"
|
||||
verbose_name = "Kunden-Export"
|
||||
description = "Kundendokumentation als PDF oder Word exportieren"
|
||||
version = "0.11.0"
|
||||
version = "0.16.0"
|
||||
author = "Claude"
|
||||
base_url = "customer-export"
|
||||
min_version = "4.6.8"
|
||||
|
||||
@@ -9,7 +9,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)
|
||||
@@ -47,6 +47,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=list(headers), rows=[[fmt(c) for c in r] for r in rows])
|
||||
|
||||
@@ -56,18 +61,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):
|
||||
|
||||
@@ -53,7 +53,7 @@ def disk_blocks(scope, opts):
|
||||
by_device.setdefault(disk.device, []).append(disk)
|
||||
|
||||
show_installed = bool(opts.get("disk_install_date"))
|
||||
headers = ["Steckplatz", "Status", "Typ", "Hersteller / Modell", "Größe", "Seriennummer", "Firmware", "RAID"]
|
||||
headers = ["Steckplatz", "Status", "Datenträger", "Größe", "Seriennummer", "RAID"]
|
||||
headers += ["Eingebaut"] * show_installed + ["Garantie bis", "Hinweise"]
|
||||
blocks = []
|
||||
for device, items in by_device.items():
|
||||
@@ -89,12 +89,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)))
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""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 .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(
|
||||
[
|
||||
("Standort", plan.site),
|
||||
("Lokation", plan.location),
|
||||
("Mandant", plan.tenant),
|
||||
("Raumgröße", f"{meters(plan.width)} × {meters(plan.depth)} m"),
|
||||
("Beschreibung", 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(f"Raumplan konnte nicht erzeugt werden: {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"
|
||||
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))
|
||||
if plan.comments:
|
||||
blocks.append(P(plan.comments))
|
||||
return blocks
|
||||
@@ -66,6 +66,7 @@ class ExportForm(forms.Form):
|
||||
)
|
||||
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")
|
||||
|
||||
topo_details = forms.MultipleChoiceField(
|
||||
choices=(("model", "Modell"), ("primary_ip", "Management-IP"), ("ports", "Ports an Verbindungen")),
|
||||
@@ -75,7 +76,11 @@ class ExportForm(forms.Form):
|
||||
label="Beschriftung",
|
||||
)
|
||||
topo_scope = forms.MultipleChoiceField(
|
||||
choices=(("site", "Gesamtes Netzwerk (je Standort)"), ("rack", "Je Rack")),
|
||||
choices=(
|
||||
("site", "Gesamtes Netzwerk (je Standort)"),
|
||||
("locations", "Lokationsübersicht (Verbindungen zwischen Lokationen)"),
|
||||
("rack", "Je Rack"),
|
||||
),
|
||||
initial=["site"],
|
||||
required=False,
|
||||
widget=forms.CheckboxSelectMultiple,
|
||||
@@ -108,6 +113,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,50 @@
|
||||
"""CPU & RAM aus dem Plugin Netbox-Utilities (netbox_utilities.DeviceHardware)."""
|
||||
from django.apps import apps
|
||||
|
||||
|
||||
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} Kerne / {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)
|
||||
@@ -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
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
import zipfile
|
||||
from io import BytesIO
|
||||
|
||||
@@ -18,6 +19,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
|
||||
@@ -138,6 +144,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
|
||||
@@ -167,9 +205,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"):
|
||||
@@ -209,8 +256,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-Grafik nicht verfügbar)")
|
||||
cap = t.cell(1, i).paragraphs[0]
|
||||
|
||||
@@ -5,7 +5,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 = {
|
||||
@@ -81,6 +81,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,
|
||||
|
||||
@@ -7,7 +7,8 @@ from django.apps import apps
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
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
|
||||
|
||||
@@ -52,10 +53,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 = f" / HE {d.position:g}" if d.position else ""
|
||||
pos = f" / HE {num(d.position)}" if d.position else ""
|
||||
return f"{d.rack}{pos}"
|
||||
|
||||
|
||||
@@ -71,6 +82,8 @@ DEVICE_COLUMNS = OrderedDict(
|
||||
("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)),
|
||||
@@ -171,12 +184,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, f"Standort {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"))
|
||||
for rack in loc_racks:
|
||||
blocks.append(H(4, f"Rack {rack.name}"))
|
||||
rack_heading = H(4, f"Rack {rack.name}")
|
||||
blocks.append(rack_heading)
|
||||
blocks.append(
|
||||
KV(
|
||||
[
|
||||
@@ -220,16 +235,52 @@ def racks(scope, opts):
|
||||
T(
|
||||
["HE", "Gerät", "Hersteller / Modell", "Seite"],
|
||||
[
|
||||
[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, "Anhang: Rack-Fotos"))
|
||||
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 ""))
|
||||
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="↑ "))
|
||||
n = len(images)
|
||||
return [REF(f"Anhang Rack-Fotos – Rack {rack.name}", heading.anchor, prefix=f"{n} Foto{'s' if n != 1 else ''}, siehe ")]
|
||||
|
||||
|
||||
@section("devices", "Geräte", "Infrastruktur", hint="Tabellen je Geräterolle")
|
||||
def devices(scope, opts):
|
||||
blocks = [H(1, "Geräte")]
|
||||
@@ -259,11 +310,22 @@ def disks(scope, opts):
|
||||
|
||||
blocks = [H(1, "Datenträger & RAID")]
|
||||
if not disks_utilities.is_installed():
|
||||
return _empty(opts, blocks, "Netbox-Utilities mit Datenträger-Verwaltung ist nicht installiert – siehe README.")
|
||||
return _empty(opts, blocks, "Keine Datenträger erfasst.")
|
||||
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)")
|
||||
def floorplans(scope, opts):
|
||||
from . import floorplan
|
||||
|
||||
blocks = [H(1, "Raumpläne")]
|
||||
if not floorplan.is_installed():
|
||||
return _empty(opts, blocks, "Keine Raumpläne erfasst.")
|
||||
blocks += floorplan.floorplan_blocks(scope, opts)
|
||||
return blocks if len(blocks) > 1 else _empty(opts, blocks, "Keine Raumpläne erfasst.")
|
||||
|
||||
|
||||
@section("power", "Stromversorgung", "Infrastruktur", default=False, hint="Power Panels & Feeds")
|
||||
def power(scope, opts):
|
||||
qs = scope.power_feeds().select_related("power_panel", "rack").order_by("power_panel__name", "name")
|
||||
@@ -279,6 +341,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", "Virtualisierungs-Cluster", "Infrastruktur", default=False, hint="Hosts und Ressourcen je Cluster")
|
||||
def clusters(scope, opts):
|
||||
qs = scope.clusters().select_related("type", "group", "tenant").order_by("group__name", "name")
|
||||
blocks = [H(1, "Virtualisierungs-Cluster")]
|
||||
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, f"Cluster {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),
|
||||
]))
|
||||
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", "Hersteller / Modell", "CPU", "RAM", "VMs", "vCPU", "RAM 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."))
|
||||
|
||||
blocks.append(T(["Cluster", "Typ", "Hosts", "VMs aktiv / gesamt", "vCPU / Kerne", "RAM VMs / Hosts", "Speicher"], summary))
|
||||
return blocks + details
|
||||
|
||||
|
||||
@section("vms", "Virtuelle Maschinen", "Infrastruktur", default=False, hint="Cluster, Ressourcen, IP")
|
||||
def vms(scope, opts):
|
||||
qs = scope.virtual_machines().select_related("cluster", "role", "platform", "primary_ip4", "primary_ip6").order_by("cluster__name", "name")
|
||||
@@ -445,7 +601,7 @@ def licenses(scope, opts):
|
||||
|
||||
@section("topology", "Netzwerk-Topologie", "Netzwerk", default=False, hint="Diagramm mit Symbolen, wie 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, "Netzwerk-Topologie")
|
||||
scopes = opts.get("topo_scope") or ["site"]
|
||||
@@ -453,6 +609,9 @@ 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, "Lokationsübersicht")] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(locs)]
|
||||
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)
|
||||
|
||||
@@ -8,12 +8,14 @@ from io import BytesIO
|
||||
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)),
|
||||
@@ -31,7 +33,7 @@ KINDS = OrderedDict(
|
||||
]
|
||||
)
|
||||
HIDDEN = "hidden"
|
||||
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k != "cloud"] + [(HIDDEN, "In Topologie ausblenden")]
|
||||
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k not in ("cloud", "location")] + [(HIDDEN, "In Topologie ausblenden")]
|
||||
|
||||
# Reihenfolge wichtig: erster Treffer gewinnt. None = passiv, nicht zeichnen.
|
||||
# Tippvarianten („Acces Point“, „Controler“, „Libary“) sind absichtlich mit abgedeckt.
|
||||
@@ -286,6 +288,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))
|
||||
@@ -319,6 +338,8 @@ _DRAWERS = {
|
||||
"tape": _draw_tape,
|
||||
"ups": _draw_ups,
|
||||
"pbx": _draw_pbx,
|
||||
"patchpanel": _draw_patchpanel,
|
||||
"location": _draw_location,
|
||||
}
|
||||
|
||||
|
||||
@@ -366,6 +387,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">
|
||||
|
||||
@@ -25,6 +25,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">
|
||||
@@ -131,6 +138,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> Rack-Fotos</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>
|
||||
{% 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>
|
||||
{% 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>
|
||||
</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> Topologie</span>
|
||||
@@ -141,7 +175,7 @@
|
||||
<div class="card-body">
|
||||
<div class="ce-label mt-0">Umfang</div>
|
||||
{% include 'netbox_customer_export/_pills.html' with field=form.topo_scope %}
|
||||
<div class="form-text mb-2">„Je Rack“ zeigt zusätzlich jedes Rack einzeln; verbundene Geräte außerhalb erscheinen gestrichelt.</div>
|
||||
<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>
|
||||
{% include 'netbox_customer_export/_pills.html' with field=form.topo_details %}
|
||||
<div class="ce-label">Weiteres</div>
|
||||
|
||||
@@ -17,6 +17,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
|
||||
@@ -27,6 +28,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
|
||||
@@ -206,6 +208,123 @@ def _collect(scope, opts):
|
||||
return by_pk, drawn, links, external
|
||||
|
||||
|
||||
def build_location_graphs(scope, opts):
|
||||
"""Lokationsübersicht: ein Graph je Standort, Knoten = Lokationen, Linien = Kabel zwischen Lokationen.
|
||||
|
||||
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(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():
|
||||
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 ""))
|
||||
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)
|
||||
graphs.append(Graph(f"Standort {site}", 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 "Kabel"] += 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)
|
||||
@@ -232,7 +351,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)
|
||||
@@ -301,6 +420,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 "")
|
||||
|
||||
@@ -41,7 +41,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)
|
||||
@@ -57,6 +59,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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "netbox-customer-export"
|
||||
version = "0.11.0"
|
||||
version = "0.16.0"
|
||||
description = "NetBox-Plugin: Kundendokumentation (PDF/Word) für Standorte, Lokationen, Mandanten und Mandantengruppen"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
Reference in new issue
Block a user