diff --git a/README.md b/README.md index fcf280a..72276ec 100644 --- a/README.md +++ b/README.md @@ -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) 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) | +| 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`) | @@ -305,6 +305,14 @@ 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 diff --git a/netbox_customer_export/__init__.py b/netbox_customer_export/__init__.py index 1e7e184..ce25f7d 100644 --- a/netbox_customer_export/__init__.py +++ b/netbox_customer_export/__init__.py @@ -5,7 +5,7 @@ class CustomerExportConfig(PluginConfig): name = "netbox_customer_export" verbose_name = "Kunden-Export" description = "Kundendokumentation als PDF oder Word exportieren" - version = "0.15.1" + version = "0.16.0" author = "Claude" base_url = "customer-export" min_version = "4.6.8" diff --git a/netbox_customer_export/floorplan.py b/netbox_customer_export/floorplan.py new file mode 100644 index 0000000..63276b8 --- /dev/null +++ b/netbox_customer_export/floorplan.py @@ -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'') + elif t in ("wall", "door"): + parts.append(f'') + if t == "door": + parts.append(f'') + elif t == "window": + parts.append(f'') + elif t == "column": + parts.append(f'' + f'') + elif t in FILLED: + parts.append(f'') + if t == "rack": + fh = min(h * 0.12, 10) + parts.append(f'') + 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'{escape(text)}') + transform = f' transform="rotate({item.rotation} {cx} {cy})"' if item.rotation else "" + return f'{"".join(parts)}' + + +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'' + vw, vh = width + 2 * m, depth + 2 * m + px = 1600 / vw # feste Pixelgröße für Renderer ohne viewBox-Skalierung + return ( + f'' + f'' + f'{bg}' + f'{"".join(_item_svg(i) for i in items)}' + f'' + f'{meters(width)} m' + f'{meters(depth)} m' + f"" + ) + + +# --- 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 diff --git a/netbox_customer_export/sections.py b/netbox_customer_export/sections.py index accf5c2..61d509b 100644 --- a/netbox_customer_export/sections.py +++ b/netbox_customer_export/sections.py @@ -315,6 +315,17 @@ def disks(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") diff --git a/pyproject.toml b/pyproject.toml index 53e370d..be4d8e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "netbox-customer-export" -version = "0.15.1" +version = "0.16.0" description = "NetBox-Plugin: Kundendokumentation (PDF/Word) für Standorte, Lokationen, Mandanten und Mandantengruppen" readme = "README.md" requires-python = ">=3.10"