Compare commits

..
21 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 cce6e21a09 feat(i18n): translate UI to English and German
Use English as source language for all user-visible strings, wrap them for
translation and ship a German catalog. Add a test that keeps the README's
NetBox range in sync with min_version/max_version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 21:25:38 +01:00
MrBlakeandClaude Opus 5.5 133cb1d9fc docs: add screenshots and generalise README
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:57:59 +01:00
MrBlakeandClaude Opus 5.5 e4d1383e8c Pass a relative path to static() for device images
A leading slash made static file finders, such as the one used by the debug toolbar with DEBUG = True, raise SuspiciousFileOperation on the Images page. The generated URL is unchanged. Verified on NetBox 4.7.2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 15:08:50 +02:00
MrBlakeandClaude Opus 5.5 ffe594a5f9 docs: rewrite README in English with standard structure
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 13:37:00 +02:00
MrBlakeandClaude Sonnet 5 4a12037ac4 fix: show wireless links between devices only reachable via other cables
WirelessLink lookups only matched devices already in the selected racks
(device_ids), so a link between two purely external devices that were
pulled into the topology only as endpoints of unrelated cables (e.g. two
outdoor radios each cabled to something inside the selected racks) never
showed up, even though both endpoint nodes were already rendered.

Now the wireless query also matches devices discovered via the cable
pass (topology_nodes), so links between already-visible external nodes
are drawn too.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 12:01:02 +02:00
MrBlakeandClaude Sonnet 5 f08df4fd52 fix: detect power cables by termination type and move toggle into topology card
Power-cable detection previously relied on cable.type, which is usually
unset for power patch cables (e.g. PDU-to-PDU), so they never got the
distinct color. Power cables are now also detected by termination
component type (PowerPort/PowerOutlet/PowerFeed).

Wireless/power display is now toggled client-side via checkboxes in the
Kabeltopologie card header (before the SVG/PNG/draw.io export buttons)
instead of a server round-trip through the top filter form, so toggling
is instant and affects exports too.

Bump plugin version to 4.5.2.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:45:27 +02:00
MrBlakeandClaude Sonnet 5 2e43166949 feat: declare NetBox 4.7.x support and add wireless/power toggle to Kabeltopologie
Adds min_version/max_version to the plugin config for NetBox 4.7.x and
extends the rack view's cable topology with optional wireless and power
cable display, rendered with distinct colors and dash patterns from
regular network cables.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:36:47 +02:00
MrBlake 86a8daf45e Merge branch 'develop' of https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views into develop 2026-08-06 14:38:20 +02:00
MrBlake f706db754c fix: respect rack unit numbering direction and starting unit 2026-08-06 14:38:16 +02:00
MrBlake c49270fab0 x 2026-07-28 15:06:14 +02:00
MrBlake 6ff2b60bb4 fix: enforce flex layout for topology device spacing 2026-07-28 15:00:32 +02:00
MrBlake ef1ad4d607 fix: enforce topology spacing and light-mode cable highlights 2026-07-28 14:58:13 +02:00
MrBlake a1d28e922d fix: improve cable count badge contrast 2026-07-28 14:48:33 +02:00
MrBlake d9d2e4dd59 fix: detect NetBox theme for topology cable highlights 2026-07-28 14:47:39 +02:00
MrBlake cff9282a60 style: use green cable highlights in light mode 2026-07-28 14:43:20 +02:00
MrBlake 1f80ae5099 fix: improve topology spacing zoom scrolling and wireless support 2026-07-28 14:42:41 +02:00
MrBlake 4680209d83 feat: add fullscreen topology and wireless links 2026-07-28 14:36:08 +02:00
MrBlake bb0693bef7 fix: sort topology devices without rendering rack elevations 2026-07-28 14:32:34 +02:00
MrBlake 1de5ed0565 feat: align topology nodes with racks and add theme-aware exports 2026-07-28 14:26:28 +02:00
MrBlake 1ff68d7026 fix: export all rendered devices from rack elevations 2026-07-22 13:33:49 +02:00
MrBlake 944652f66c feat: export editable draw.io rack and topology elements 2026-07-22 13:31:05 +02:00
46 changed files with 2036 additions and 427 deletions

No files matched your search

+2 -1
View File
@@ -1,4 +1,5 @@
recursive-include netbox_topology_views/static * recursive-include netbox_topology_views/static *
recursive-include netbox_topology_views/templates * recursive-include netbox_topology_views/templates *
recursive-include netbox_topology_views/api * recursive-include netbox_topology_views/api *
prune netbox_topology_views/api/__pycache__ prune netbox_topology_views/api/__pycache__
recursive-include netbox_topology_views/locale *.po *.mo
+148 -133
View File
@@ -1,84 +1,105 @@
# MRB NetBox Topology Views # MRB NetBox Topology Views
Ein angepasster Fork von **NetBox Topology Views** mit erweiterten Rack-Ansichten, A customised fork of **NetBox Topology Views** with extended rack views,
interaktiver Kabelverfolgung und zusätzlichen Netzwerk-Icons. interactive cable tracing and additional network icons.
Das Plugin erzeugt Topologien aus den in NetBox gepflegten Geräten, Ports und The plugin builds topologies from the devices, ports and cables maintained in
Kabeln. Neben der klassischen Topologie bietet dieser Fork eine vollständige NetBox. In addition to the classic topology, this fork provides a complete view
Darstellung einzelner oder mehrerer Racks einschließlich Vorderseite, of one or more racks including front, rear and cabling.
Rückseite und Verkabelung.
## Vorteile dieses Forks | | |
|---|---|
| **Plugin name** | `netbox_topology_views` |
| **Package** | `netbox-topology-views` |
| **NetBox** | `4.7.x` |
| **Python** | see `setup.py` |
| **Repository** | <https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views> |
- Ein oder mehrere Racks gemeinsam anzeigen ## Screenshots
- Geräte positionsgenau anhand ihrer Höheneinheiten darstellen
- Vorder- und Rückseite eines Racks getrennt betrachten
- Rackübergreifende und externe Kabelverbindungen erkennen
- Geräte in der Kabeltopologie frei verschieben
- Manuelle Positionen pro Rack-Auswahl im Browser speichern
- Verbindungen eines Geräts beim Hover weiß hervorheben
- Alle verbundenen Ports und Gegenstellen eines Geräts anzeigen
- Schnittstellen eines Kabels beim Hover anzeigen
- Geräte und Kabel direkt aus der Topologie in NetBox öffnen
- Einzelne Racks, alle Racks oder die Kabeltopologie als SVG, PNG und draw.io exportieren
- Exporte grundsätzlich mit transparentem Hintergrund erzeugen
- Topologie als PNG oder diagrams.net/draw.io-XML exportieren
- Zusätzliche Icons für Network-, Leaf-, Spine- und Aggregation-Switche
- Unterstützung für helle und dunkle NetBox-Themes
## Änderungen gegenüber dem Original Cable topology of a site, arranged with a coordinate group:
Dieser Fork ergänzt insbesondere: ![Topology view](docs/screenshots/topology.png)
1. Die neue Menükategorie **Weitere Ansichten**. Rack view with front and rear elevations:
2. Eine Rack-Ansicht mit Filtern für Site, Location und mehrere Racks.
3. Positionsgenaue Rack-Elevations für Vorder- und Rückseite.
4. Eine Kabeltabelle mit A- und B-Terminierungen.
5. Eine interaktive, verschiebbare Kabeltopologie unter den Racks.
6. Hover-Hervorhebung und Port-zu-Port-Verfolgung für Geräte und Kabel.
7. Lokal gespeicherte Gerätepositionen und eine Funktion zum Zurücksetzen.
8. Ein erweitertes, skalierbares SVG-Iconset für Switch-Rollen.
9. Transparente SVG-, PNG- und draw.io-Exporte für Rack- und Topologieansichten.
10. Anpassungen für die Verwendung mit NetBox 4.6, darunter die geänderte
`Rack.units`-Property.
## Vorschau ![Rack view](docs/screenshots/rack-view.png)
Die klassische Topologieansicht stammt aus dem ursprünglichen Plugin: ## Features
- Show one or more racks together
- Render devices at their exact rack unit position
- View front and rear of a rack separately
- Ascending/descending U numbering and custom starting unit are respected automatically
- Detect cross-rack and external cable connections
- Freely move devices in the cable topology
- Sort devices in the cable topology by rack position within each rack
- Browser full-screen mode for the cable topology
- Zoom the cable topology between 50 and 200 % and scroll in full-screen
- Render P2P wireless links and multi-access WLANs as purple dashed radio links
- Optionally show/hide wireless links and power cables in the rack view's cable topology, visually distinct from network cables (purple dashed / orange dotted)
- Store manual positions per rack selection in the browser
- Highlight a device's connections in white on hover
- Show all connected ports and peers of a device
- Show a cable's terminations on hover
- Open devices and cables in NetBox directly from the topology
- Export single racks, all racks or the cable topology as SVG, PNG and draw.io — always with transparent background
- Colours of rack view and export follow the active light or dark mode
- Additional icons for network, leaf, spine and aggregation switches
### Changes compared to the original
1. New menu category **More views**.
2. A rack view with filters for site, location and multiple racks.
3. Position-accurate rack elevations for front and rear.
4. A cable table with A and B terminations.
5. An interactive, movable cable topology below the racks.
6. Hover highlighting and port-to-port tracing for devices and cables.
7. Locally stored device positions and a reset function.
8. An extended, scalable SVG icon set for switch roles.
9. Transparent SVG, PNG and draw.io exports for rack and topology views.
10. Adjustments for NetBox 4.6+, including the changed `Rack.units` property.
![Topology in light mode](doc/img/topology_light.png) ![Topology in light mode](doc/img/topology_light.png)
![Topology in dark mode](doc/img/topology_dark.png) ![Topology in dark mode](doc/img/topology_dark.png)
## Installation aus Gitea ## Compatibility
Das Plugin kann direkt aus dem `develop`-Branch installiert werden: - NetBox `4.7.x` (`min_version`/`max_version` in `netbox_topology_views/__init__.py`)
- Based on NetBox Topology Views `4.5.1`
Since the upstream release officially targets NetBox 4.5.x, test updates to
newer NetBox versions in a staging instance first.
## Installation
All paths assume a standard installation under `/opt/netbox`.
### 1. Install the package
```bash ```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \ /opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" "git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop"
``` ```
Für eine reproduzierbare Produktivinstallation sollte statt `develop` ein For reproducible production installs, replace `develop` with a release tag or a
Release-Tag oder ein bestimmter Commit verwendet werden: full commit ID.
### 2. Add the plugin to `local_requirements.txt`
This makes `upgrade.sh` reinstall the plugin automatically on every NetBox upgrade:
```bash ```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \ grep -qxF "git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" /opt/netbox/local_requirements.txt \
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@v4.5.1-mrb.1" || echo "git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" | sudo tee -a /opt/netbox/local_requirements.txt
``` ```
Für automatische Neuinstallationen bei einem NetBox-Upgrade wird derselbe If the repository is private, the NetBox server needs a read-only deploy token
Eintrag in `/opt/netbox/local_requirements.txt` hinterlegt: or an SSH key. Do not store credentials in `local_requirements.txt`.
```text ### 3. Enable the plugin
git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop
```
Bei einem privaten Gitea-Repository muss der NetBox-Server Zugriff über einen In `/opt/netbox/netbox/netbox/configuration.py`:
Deploy-Token oder SSH-Key erhalten.
## NetBox-Konfiguration
In `netbox/configuration.py` wird das Python-Paket aktiviert:
```python ```python
PLUGINS = [ PLUGINS = [
@@ -94,132 +115,126 @@ PLUGINS_CONFIG = {
} }
``` ```
Danach werden Migrationen und statische Dateien verarbeitet: If other plugins are already configured, add `netbox_topology_views` to the
existing list and dictionary instead of replacing them.
### 4. Apply migrations, collect static files, restart
```bash ```bash
cd /opt/netbox/netbox cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate /opt/netbox/venv/bin/python manage.py migrate netbox_topology_views
/opt/netbox/venv/bin/python manage.py collectstatic --no-input /opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq sudo systemctl restart netbox netbox-rq
``` ```
Nach Änderungen an CSS oder Icons kann ein Hard-Reload des Browsers mit After changes to CSS or icons a hard reload in the browser (`Ctrl+F5`) may be
`Strg+F5` erforderlich sein. necessary.
## Aktualisierung ## Update
```bash ```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \ /opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop" "git+https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views.git@develop"
cd /opt/netbox/netbox cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate /opt/netbox/venv/bin/python manage.py migrate netbox_topology_views
/opt/netbox/venv/bin/python manage.py collectstatic --no-input /opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq sudo systemctl restart netbox netbox-rq
``` ```
`--force-reinstall` ist derzeit sinnvoll, da der Fork intern noch die `--force-reinstall` is required because the fork still uses the internal
Paketversion `4.5.1` verwendet. package version `4.5.2`.
## Verwendung When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from
`local_requirements.txt` and runs migrations and `collectstatic`:
### Klassische Topologie ```bash
sudo /opt/netbox/upgrade.sh
sudo systemctl restart netbox netbox-rq
```
Unter **Plugins → Topology Views → Topology** steht die ursprüngliche, ## Uninstall
filterbare Topologieansicht zur Verfügung. Sie unterstützt unter anderem:
- physische Kabel 1. Remove `"netbox_topology_views"` from `PLUGINS` and `PLUGINS_CONFIG`.
- logische Verbindungen 2. Remove the line from `/opt/netbox/local_requirements.txt`.
- Nachbargeräte 3. Uninstall the package and restart NetBox:
- Circuit-Terminations
- Power Feeds
- Wireless Links
- Coordinate Groups
- PNG- und XML-Export
### Rack-Ansicht ```bash
/opt/netbox/venv/bin/pip uninstall netbox-topology-views
sudo systemctl restart netbox netbox-rq
```
Die erweiterte Ansicht befindet sich unter: ## Usage
**Plugins → Topology Views → Weitere Ansichten → Rack-Ansicht** ### Classic topology
Über Site, Location und Rack können ein einzelnes Rack oder mehrere Racks **Plugins → Topology Views → Topology** provides the original, filterable
ausgewählt werden. Optional lassen sich auch leere Racks einblenden. topology view. It supports physical cables, logical connections, neighbour
devices, circuit terminations, power feeds, wireless links, coordinate groups,
and PNG and XML export.
In der Elevation werden Geräte entsprechend ihrer Position, Gerätehöhe und ### Rack view
Rack-Seite dargestellt. Unter den Elevations folgen:
1. die interaktive Kabeltopologie und **Plugins → Topology Views → More views → Rack view**
2. eine tabellarische Übersicht sämtlicher betroffener Kabel.
In der Kabeltopologie können Geräte per Drag-and-drop verschoben werden. Beim Select a single rack or several racks via site, location and rack; empty racks
Hover über ein Gerät werden dessen Kabel hervorgehoben und alle verbundenen can be shown optionally. Devices are rendered according to position, height and
Ports aufgelistet. Beim Hover über ein Kabel erscheinen beide Terminierungen. rack face. Below the elevations follow:
Ein Klick öffnet das jeweilige NetBox-Objekt.
Über die Export-Schaltflächen können ein einzelnes Rack, alle aktuell 1. the interactive cable topology, and
angezeigten Racks oder die interaktive Kabeltopologie als SVG, PNG oder 2. a table of all involved cables.
draw.io-Datei gespeichert werden. Sämtliche Exportformate werden ohne
Hintergrundfläche erzeugt.
Die Positionen werden im `localStorage` des Browsers gespeichert. Sie gelten In the cable topology, devices can be moved via drag and drop. Hovering a device
damit nur für den jeweiligen Browser und die konkrete Rack-/Filterauswahl. highlights its cables and lists all connected ports; hovering a cable shows both
terminations. A click opens the NetBox object.
## Geräte-Icons The export buttons save a single rack, all displayed racks or the cable topology
as SVG, PNG or draw.io, always without background. In the draw.io export, rack
frames, devices and labels remain individually editable, and topology cables are
real edges that follow the devices.
Das Plugin ordnet Icons anhand des Slugs einer Device Role zu. Dieser Fork Positions are stored in the browser's `localStorage` and apply only to that
liefert zusätzlich folgende SVG-Dateien aus: browser and the specific rack/filter selection.
| Device-Role-Slug | Icon-Datei | With [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities)
installed, partial-width devices are rendered side by side in the rack view.
## Device icons
Icons are assigned by device role slug. This fork additionally ships:
| Device role slug | Icon file |
| --- | --- | | --- | --- |
| `network-switch` | `network-switch.svg` | | `network-switch` | `network-switch.svg` |
| `leaf-switch` | `leaf-switch.svg` | | `leaf-switch` | `leaf-switch.svg` |
| `spine-switch` | `spine-switch.svg` | | `spine-switch` | `spine-switch.svg` |
| `aggregation-switch` | `aggregation-switch.svg` | | `aggregation-switch` | `aggregation-switch.svg` |
Eigene Bilder können weiterhin über die Seite **Images** zugeordnet werden. Custom images can still be assigned on the **Images** page. The default path is
Der Standardpfad lautet `netbox_topology_views/img` innerhalb von `netbox_topology_views/img` within `STATIC_ROOT`.
`STATIC_ROOT`.
## Berechtigungen ## Permissions
Für die klassische Topologie werden mindestens folgende Rechte benötigt: Classic topology: `dcim.view_site`, `dcim.view_device`.
- `dcim.view_site` Rack view: `dcim.view_rack`, `dcim.view_device`, `dcim.view_cable`.
- `dcim.view_device`
Für die Rack-Ansicht werden benötigt: Saving classic topology coordinates additionally requires the corresponding
permissions on `netbox_topology_views.coordinate`.
- `dcim.view_rack` ## Origin and credits
- `dcim.view_device`
- `dcim.view_cable`
Für das Speichern klassischer Topologiekoordinaten werden zusätzlich die This project is a fork of the open-source plugin
entsprechenden Rechte auf `netbox_topology_views.coordinate` benötigt.
## Kompatibilität
Die Basis dieses Forks ist NetBox Topology Views `4.5.1`. Die neuen
Rack-Funktionen wurden für den Einsatz mit NetBox `4.6.5` angepasst. Da das
ursprüngliche Release offiziell für NetBox 4.5.x ausgewiesen ist, sollten
Updates auf neuere NetBox-Versionen zunächst in einer Testumgebung geprüft
werden.
## Ursprung und Danksagung
Dieses Projekt ist ein Fork des Open-Source-Plugins
[NetBox Topology Views](https://github.com/mattieserver/netbox-topology-views). [NetBox Topology Views](https://github.com/mattieserver/netbox-topology-views).
The original plugin was created by **Mattijs Vanhaverbeke**. Most of the classic
topology view, data models, filters and export functions are based on his work
and the contributions to the original project.
Das ursprüngliche Plugin wurde von **Mattijs Vanhaverbeke** erstellt. Der This fork is developed independently and is not officially affiliated with the
größte Teil der klassischen Topologieansicht, Datenmodelle, Filter und original author or the NetBox project.
Exportfunktionen basiert auf seiner Arbeit und den Beiträgen des ursprünglichen
Projekts.
Dieser Fork wird unabhängig weiterentwickelt und ist nicht mit dem ## License
ursprünglichen Autor oder dem NetBox-Projekt offiziell verbunden.
## Lizenz Like the original, this project is licensed under the
[Apache License 2.0](LICENSE). Existing copyright, license and attribution
Das Projekt steht wie das Original unter der notices of the original project are retained.
[Apache License 2.0](LICENSE). Bestehende Copyright-, Lizenz- und
Urheberhinweise des ursprünglichen Projekts bleiben erhalten.
Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

+7 -4
View File
@@ -1,14 +1,17 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginConfig from netbox.plugins import PluginConfig
class TopologyViewsConfig(PluginConfig): class TopologyViewsConfig(PluginConfig):
name = "netbox_topology_views" name = "netbox_topology_views"
verbose_name = "Topology views" verbose_name = _("Topology views")
description = "A plugin to render topology maps" description = _("A plugin to render topology maps")
version = "4.5.1" version = "4.5.2"
author = "Mattijs Vanhaverbeke" author = "Mattijs Vanhaverbeke, Codex & Claude"
author_email = "[email protected]" author_email = "[email protected]"
base_url = "netbox_topology_views" base_url = "netbox_topology_views"
min_version = "4.7.0"
max_version = "4.7.99"
required_settings = [] required_settings = []
default_settings = { default_settings = {
"static_image_directory": "netbox_topology_views/img", "static_image_directory": "netbox_topology_views/img",
+16 -15
View File
@@ -1,3 +1,4 @@
from django.utils.translation import gettext_lazy as _
from utilities.choices import ChoiceSet from utilities.choices import ChoiceSet
class NodeLabelItems(ChoiceSet): class NodeLabelItems(ChoiceSet):
@@ -18,19 +19,19 @@ class NodeLabelItems(ChoiceSet):
ASSET_TAG = 'assettag' ASSET_TAG = 'assettag'
CHOICES = [ CHOICES = [
(DEVICE_NAME, 'Device Name'), (DEVICE_NAME, _('Device Name')),
(DEVICE_TYPE, 'Device Type'), (DEVICE_TYPE, _('Device Type')),
(ROLE, 'Role'), (ROLE, _('Role')),
(DESCRIPTION, 'Description'), (DESCRIPTION, _('Description')),
(PRIMARY_IPV4, 'Primary IPv4'), (PRIMARY_IPV4, _('Primary IPv4')),
(PRIMARY_IPV6, 'Primary IPv6'), (PRIMARY_IPV6, _('Primary IPv6')),
(OUT_OF_BAND_IP, 'Out-of-band IP'), (OUT_OF_BAND_IP, _('Out-of-band IP')),
(PLATFORM, 'Platform'), (PLATFORM, _('Platform')),
(SERIAL, 'Serial'), (SERIAL, _('Serial')),
(TENANT, 'Tenant'), (TENANT, _('Tenant')),
(SITE, 'Site'), (SITE, _('Site')),
(LOCATION, 'Location'), (LOCATION, _('Location')),
(RACK, 'Rack'), (RACK, _('Rack')),
(VIRTUAL_CHASSIS, 'Virtual Chassis'), (VIRTUAL_CHASSIS, _('Virtual Chassis')),
(ASSET_TAG, 'Asset Tag'), (ASSET_TAG, _('Asset Tag')),
] ]
+23 -22
View File
@@ -3,6 +3,7 @@ from circuits.models import Circuit
from dcim.choices import DeviceStatusChoices from dcim.choices import DeviceStatusChoices
from dcim.models import Device, DeviceRole, Location, Rack, Region, Site, SiteGroup, Manufacturer, DeviceType, Platform, PowerPanel, PowerFeed from dcim.models import Device, DeviceRole, Location, Rack, Region, Site, SiteGroup, Manufacturer, DeviceType, Platform, PowerPanel, PowerFeed
from django.db.models import Q from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from extras.filtersets import LocalConfigContextFilterSet from extras.filtersets import LocalConfigContextFilterSet
from extras.models import ConfigTemplate from extras.models import ConfigTemplate
from netbox.filtersets import NetBoxModelFilterSet from netbox.filtersets import NetBoxModelFilterSet
@@ -13,58 +14,58 @@ from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoo
class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet): class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilterSet, LocalConfigContextFilterSet):
q = django_filters.CharFilter( q = django_filters.CharFilter(
method="search", method="search",
label="Search", label=_("Search"),
) )
manufacturer_id = django_filters.ModelMultipleChoiceFilter( manufacturer_id = django_filters.ModelMultipleChoiceFilter(
field_name='device_type__manufacturer', field_name='device_type__manufacturer',
queryset=Manufacturer.objects.all(), queryset=Manufacturer.objects.all(),
label="Manufacturer (ID)", label=_("Manufacturer (ID)"),
) )
manufacturer = django_filters.ModelMultipleChoiceFilter( manufacturer = django_filters.ModelMultipleChoiceFilter(
field_name='device_type__manufacturer__slug', field_name='device_type__manufacturer__slug',
queryset=Manufacturer.objects.all(), queryset=Manufacturer.objects.all(),
to_field_name='slug', to_field_name='slug',
label="Manufacturer (slug)", label=_("Manufacturer (slug)"),
) )
device_type_id = django_filters.ModelMultipleChoiceFilter( device_type_id = django_filters.ModelMultipleChoiceFilter(
queryset=DeviceType.objects.all(), queryset=DeviceType.objects.all(),
label="Device type (ID)", label=_("Device type (ID)"),
) )
role_id = django_filters.ModelMultipleChoiceFilter( role_id = django_filters.ModelMultipleChoiceFilter(
field_name="role_id", field_name="role_id",
queryset=DeviceRole.objects.all(), queryset=DeviceRole.objects.all(),
label="Role (ID)", label=_("Role (ID)"),
) )
platform_id = django_filters.ModelMultipleChoiceFilter( platform_id = django_filters.ModelMultipleChoiceFilter(
queryset=Platform.objects.all(), queryset=Platform.objects.all(),
label="Platform (ID)", label=_("Platform (ID)"),
) )
region_id = TreeNodeMultipleChoiceFilter( region_id = TreeNodeMultipleChoiceFilter(
queryset=Region.objects.all(), queryset=Region.objects.all(),
field_name="site__region", field_name="site__region",
lookup_expr="in", lookup_expr="in",
label="Region (ID)", label=_("Region (ID)"),
) )
site_group_id = TreeNodeMultipleChoiceFilter( site_group_id = TreeNodeMultipleChoiceFilter(
queryset=SiteGroup.objects.all(), queryset=SiteGroup.objects.all(),
field_name="site__group", field_name="site__group",
lookup_expr="in", lookup_expr="in",
label="Site Group (ID)", label=_("Site Group (ID)"),
) )
site_id = django_filters.ModelMultipleChoiceFilter( site_id = django_filters.ModelMultipleChoiceFilter(
queryset=Site.objects.all(), queryset=Site.objects.all(),
label="Site (ID)", label=_("Site (ID)"),
) )
location_id = TreeNodeMultipleChoiceFilter( location_id = TreeNodeMultipleChoiceFilter(
queryset=Location.objects.all(), queryset=Location.objects.all(),
field_name="location", field_name="location",
lookup_expr="in", lookup_expr="in",
label="Location (ID)", label=_("Location (ID)"),
) )
rack_id = django_filters.ModelMultipleChoiceFilter( rack_id = django_filters.ModelMultipleChoiceFilter(
queryset=Rack.objects.all(), queryset=Rack.objects.all(),
field_name="rack_id", field_name="rack_id",
label="Rack (ID)", label=_("Rack (ID)"),
) )
status = django_filters.MultipleChoiceFilter( status = django_filters.MultipleChoiceFilter(
choices=DeviceStatusChoices, choices=DeviceStatusChoices,
@@ -72,50 +73,50 @@ class DeviceFilterSet(NetBoxModelFilterSet, TenancyFilterSet, ContactModelFilter
) )
mac_address = MultiValueMACAddressFilter( mac_address = MultiValueMACAddressFilter(
field_name='interfaces__mac_addresses__mac_address', field_name='interfaces__mac_addresses__mac_address',
label="MAC address", label=_("MAC address"),
) )
serial = MultiValueCharFilter( serial = MultiValueCharFilter(
lookup_expr='iexact' lookup_expr='iexact'
) )
console_ports = django_filters.BooleanFilter( console_ports = django_filters.BooleanFilter(
method='_console_ports', method='_console_ports',
label="Has console ports", label=_("Has console ports"),
) )
console_server_ports = django_filters.BooleanFilter( console_server_ports = django_filters.BooleanFilter(
method='_console_server_ports', method='_console_server_ports',
label="Has console server ports", label=_("Has console server ports"),
) )
power_ports = django_filters.BooleanFilter( power_ports = django_filters.BooleanFilter(
method='_power_ports', method='_power_ports',
label="Has power ports", label=_("Has power ports"),
) )
power_outlets = django_filters.BooleanFilter( power_outlets = django_filters.BooleanFilter(
method='_power_outlets', method='_power_outlets',
label="Has power outlets", label=_("Has power outlets"),
) )
interfaces = django_filters.BooleanFilter( interfaces = django_filters.BooleanFilter(
method='_interfaces', method='_interfaces',
label="Has interfaces", label=_("Has interfaces"),
) )
pass_through_ports = django_filters.BooleanFilter( pass_through_ports = django_filters.BooleanFilter(
method='_pass_through_ports', method='_pass_through_ports',
label="Has pass-through ports", label=_("Has pass-through ports"),
) )
config_template_id = django_filters.ModelMultipleChoiceFilter( config_template_id = django_filters.ModelMultipleChoiceFilter(
queryset=ConfigTemplate.objects.all(), queryset=ConfigTemplate.objects.all(),
label="Config template (ID)", label=_("Config template (ID)"),
) )
has_primary_ip = django_filters.BooleanFilter( has_primary_ip = django_filters.BooleanFilter(
method='_has_primary_ip', method='_has_primary_ip',
label="Has a primary IP", label=_("Has a primary IP"),
) )
has_oob_ip = django_filters.BooleanFilter( has_oob_ip = django_filters.BooleanFilter(
method='_has_oob_ip', method='_has_oob_ip',
label="Has an out-of-band IP", label=_("Has an out-of-band IP"),
) )
virtual_chassis_member = django_filters.BooleanFilter( virtual_chassis_member = django_filters.BooleanFilter(
method='_virtual_chassis_member', method='_virtual_chassis_member',
label="Is a virtual chassis member", label=_("Is a virtual chassis member"),
) )
class Meta: class Meta:
+6 -7
View File
@@ -1,4 +1,3 @@
from cProfile import label
from django import forms from django import forms
from django.conf import settings from django.conf import settings
@@ -159,7 +158,7 @@ class DeviceFilterForm(
platform_id = DynamicModelMultipleChoiceField( platform_id = DynamicModelMultipleChoiceField(
queryset=Platform.objects.all(), queryset=Platform.objects.all(),
required=False, required=False,
null_option='None', null_option=_('None'),
label=_('Platform') label=_('Platform')
) )
console_ports = forms.NullBooleanField( console_ports = forms.NullBooleanField(
@@ -649,7 +648,7 @@ class IndividualOptionsForm(NetBoxModelForm):
'are displayed as yellow dotted lines.') 'are displayed as yellow dotted lines.')
) )
show_single_cable_logical_conns = forms.BooleanField( show_single_cable_logical_conns = forms.BooleanField(
label = ('Show redundant Cable and Logical Connection'), label = _('Show redundant Cable and Logical Connection'),
required = False, required = False,
initial=False, initial=False,
help_text=_('Shows a logical connection (in addition to a cable), ' help_text=_('Shows a logical connection (in addition to a cable), '
@@ -694,28 +693,28 @@ class IndividualOptionsForm(NetBoxModelForm):
'same virtual chassis.') 'same virtual chassis.')
) )
draw_default_layout = forms.BooleanField( draw_default_layout = forms.BooleanField(
label = ('Draw Default Layout'), label = _('Draw Default Layout'),
required=False, required=False,
initial=False, initial=False,
help_text=_('Enable this option if you want to draw the topology on ' help_text=_('Enable this option if you want to draw the topology on '
'the initial load (when you go to the topology plugin page).') 'the initial load (when you go to the topology plugin page).')
) )
straight_cables = forms.BooleanField( straight_cables = forms.BooleanField(
label=('Use Straight Cables'), label=_('Use Straight Cables'),
required=False, required=False,
initial=False, initial=False,
help_text=_('Enable this option if you want to draw cables as straight lines ' help_text=_('Enable this option if you want to draw cables as straight lines '
'instead of curves.') 'instead of curves.')
) )
draw_termination_labels = forms.BooleanField( draw_termination_labels = forms.BooleanField(
label=('Termination Labels'), label=_('Termination Labels'),
required=False, required=False,
initial=False, initial=False,
help_text=_('Enable this option if you want to draw a label on each ' help_text=_('Enable this option if you want to draw a label on each '
'cable end.') 'cable end.')
) )
draw_cable_labels = forms.BooleanField( draw_cable_labels = forms.BooleanField(
label=('Cable Labels'), label=_('Cable Labels'),
required=False, required=False,
initial=False, initial=False,
help_text=_('Enable this option if you want to draw a cable labels.') help_text=_('Enable this option if you want to draw a cable labels.')
File diff suppressed because it is too large. Load diff
+60 -33
View File
@@ -9,6 +9,7 @@ from django.contrib.contenttypes.models import ContentType
from django.db import models from django.db import models
from django.templatetags.static import static from django.templatetags.static import static
from django.urls import reverse from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from netbox.models import NetBoxModel from netbox.models import NetBoxModel
from netbox.models.features import ( from netbox.models.features import (
ChangeLoggingMixin, ChangeLoggingMixin,
@@ -29,13 +30,15 @@ from netbox_topology_views.choices import NodeLabelItems
class RoleImage(ChangeLoggingMixin, ExportTemplatesMixin, EventRulesMixin): class RoleImage(ChangeLoggingMixin, ExportTemplatesMixin, EventRulesMixin):
class Meta: class Meta:
verbose_name = _('role image')
verbose_name_plural = _('role images')
indexes = [ indexes = [
models.Index(fields=["content_type", "object_id"]), models.Index(fields=["content_type", "object_id"]),
] ]
objects: "models.Manager[RoleImage]" objects: "models.Manager[RoleImage]"
image = models.CharField("Path within the netbox static directory", max_length=255) image = models.CharField(_("Path within the netbox static directory"), max_length=255)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True)
@@ -105,11 +108,13 @@ class CoordinateGroup(NetBoxModel):
This allows different visualizations with the same devices. This allows different visualizations with the same devices.
""" """
name = models.CharField( name = models.CharField(
verbose_name=_('name'),
max_length=100, max_length=100,
unique=True, unique=True,
) )
description = models.CharField( description = models.CharField(
verbose_name=_('description'),
max_length=255, max_length=255,
blank = True, blank = True,
) )
@@ -118,6 +123,8 @@ class CoordinateGroup(NetBoxModel):
class Meta: class Meta:
ordering = ['name'] ordering = ['name']
verbose_name = _('coordinate group')
verbose_name_plural = _('coordinate groups')
def __str__(self): def __str__(self):
return self.name return self.name
@@ -131,16 +138,18 @@ class Coordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(Device, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE, verbose_name=_('device'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField( x = models.IntegerField(
help_text='X-coordinate of the device (horizontal) on the canvas. ' verbose_name=_('X'),
'Smaller values correspond to a position further to the left on the monitor.', help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
help_text='Y-coordinate of the device (vertical) on the canvas. ' verbose_name=_('Y'),
'Smaller values correspond to a position further up on the monitor.', help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -156,9 +165,9 @@ class Coordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", name="default",
description="Automatically generated default group. If you delete " description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but " "this group, all default coordinates are gone for good but "
"the group itself will be re-created." "the group itself will be re-created.")
) )
group.save() group.save()
group_id = group.pk group_id = group.pk
@@ -169,6 +178,8 @@ class Coordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('device coordinate')
verbose_name_plural = _('device coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -182,16 +193,18 @@ class CircuitCoordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(Circuit, on_delete=models.CASCADE) device = models.ForeignKey(Circuit, on_delete=models.CASCADE, verbose_name=_('circuit'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField( x = models.IntegerField(
help_text='X-coordinate of the device (horizontal) on the canvas. ' verbose_name=_('X'),
'Smaller values correspond to a position further to the left on the monitor.', help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
help_text='Y-coordinate of the device (vertical) on the canvas. ' verbose_name=_('Y'),
'Smaller values correspond to a position further up on the monitor.', help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -207,9 +220,9 @@ class CircuitCoordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", name="default",
description="Automatically generated default group. If you delete " description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but " "this group, all default coordinates are gone for good but "
"the group itself will be re-created." "the group itself will be re-created.")
) )
group.save() group.save()
group_id = group.pk group_id = group.pk
@@ -220,6 +233,8 @@ class CircuitCoordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('circuit coordinate')
verbose_name_plural = _('circuit coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -233,16 +248,18 @@ class PowerPanelCoordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(PowerPanel, on_delete=models.CASCADE) device = models.ForeignKey(PowerPanel, on_delete=models.CASCADE, verbose_name=_('power panel'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField( x = models.IntegerField(
help_text='X-coordinate of the device (horizontal) on the canvas. ' verbose_name=_('X'),
'Smaller values correspond to a position further to the left on the monitor.', help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
help_text='Y-coordinate of the device (vertical) on the canvas. ' verbose_name=_('Y'),
'Smaller values correspond to a position further up on the monitor.', help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -258,9 +275,9 @@ class PowerPanelCoordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", name="default",
description="Automatically generated default group. If you delete " description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but " "this group, all default coordinates are gone for good but "
"the group itself will be re-created." "the group itself will be re-created.")
) )
group.save() group.save()
group_id = group.pk group_id = group.pk
@@ -271,6 +288,8 @@ class PowerPanelCoordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('power panel coordinate')
verbose_name_plural = _('power panel coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -284,16 +303,18 @@ class PowerFeedCoordinate(NetBoxModel):
position. Devices belong to one or more coordinate groups. They have to position. Devices belong to one or more coordinate groups. They have to
be unique together. be unique together.
""" """
device = models.ForeignKey(PowerFeed, on_delete=models.CASCADE) device = models.ForeignKey(PowerFeed, on_delete=models.CASCADE, verbose_name=_('power feed'))
group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE) group = models.ForeignKey(CoordinateGroup, on_delete=models.CASCADE, verbose_name=_('group'))
x = models.IntegerField( x = models.IntegerField(
help_text='X-coordinate of the device (horizontal) on the canvas. ' verbose_name=_('X'),
'Smaller values correspond to a position further to the left on the monitor.', help_text=_('X-coordinate of the device (horizontal) on the canvas. '
'Smaller values correspond to a position further to the left on the monitor.'),
) )
y = models.IntegerField( y = models.IntegerField(
help_text='Y-coordinate of the device (vertical) on the canvas. ' verbose_name=_('Y'),
'Smaller values correspond to a position further up on the monitor.', help_text=_('Y-coordinate of the device (vertical) on the canvas. '
'Smaller values correspond to a position further up on the monitor.'),
) )
_netbox_private = True _netbox_private = True
@@ -309,9 +330,9 @@ class PowerFeedCoordinate(NetBoxModel):
else: else:
group = CoordinateGroup( group = CoordinateGroup(
name="default", name="default",
description="Automatically generated default group. If you delete " description=_("Automatically generated default group. If you delete "
"this group, all default coordinates are gone for good but " "this group, all default coordinates are gone for good but "
"the group itself will be re-created." "the group itself will be re-created.")
) )
group.save() group.save()
group_id = group.pk group_id = group.pk
@@ -322,6 +343,8 @@ class PowerFeedCoordinate(NetBoxModel):
class Meta: class Meta:
ordering = ['group', 'device'] ordering = ['group', 'device']
unique_together = ('device', 'group') unique_together = ('device', 'group')
verbose_name = _('power feed coordinate')
verbose_name_plural = _('power feed coordinates')
def __str__(self): def __str__(self):
return f'{self.x};{self.y}' return f'{self.x};{self.y}'
@@ -421,5 +444,9 @@ class IndividualOptions(NetBoxModel):
_netbox_private = True _netbox_private = True
class Meta:
verbose_name = _('individual options')
verbose_name_plural = _('individual options')
def __str___(self): def __str___(self):
return f"{self.user_id}" return f"{self.user_id}"
+25 -24
View File
@@ -1,15 +1,16 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenu, PluginMenuItem, PluginMenuButton from netbox.plugins import PluginMenu, PluginMenuItem, PluginMenuButton
coordinategroup_buttons = ( coordinategroup_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinategroup_add', link='plugins:netbox_topology_views:coordinategroup_add',
title='Add', title=_('Add'),
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinategroup'] permissions=['netbox_topology_views.add_coordinategroup']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinategroup_import', link='plugins:netbox_topology_views:coordinategroup_import',
title='Import', title=_('Import'),
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinategroup'] permissions=['netbox_topology_views.add_coordinategroup']
) )
@@ -18,13 +19,13 @@ coordinategroup_buttons = (
circuitcoordinate_buttons = ( circuitcoordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:circuitcoordinate_add', link='plugins:netbox_topology_views:circuitcoordinate_add',
title='Add', title=_('Add'),
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:circuitcoordinate_import', link='plugins:netbox_topology_views:circuitcoordinate_import',
title='Import', title=_('Import'),
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
@@ -33,13 +34,13 @@ circuitcoordinate_buttons = (
powerpanelcoordinate_buttons = ( powerpanelcoordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerpanelcoordinate_add', link='plugins:netbox_topology_views:powerpanelcoordinate_add',
title='Add', title=_('Add'),
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerpanelcoordinate_import', link='plugins:netbox_topology_views:powerpanelcoordinate_import',
title='Import', title=_('Import'),
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
@@ -48,13 +49,13 @@ powerpanelcoordinate_buttons = (
powerfeedcoordinate_buttons = ( powerfeedcoordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerfeedcoordinate_add', link='plugins:netbox_topology_views:powerfeedcoordinate_add',
title='Add', title=_('Add'),
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:powerfeedcoordinate_import', link='plugins:netbox_topology_views:powerfeedcoordinate_import',
title='Import', title=_('Import'),
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
@@ -63,45 +64,45 @@ powerfeedcoordinate_buttons = (
coordinate_buttons = ( coordinate_buttons = (
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinate_add', link='plugins:netbox_topology_views:coordinate_add',
title='Add', title=_('Add'),
icon_class='mdi mdi-plus-thick', icon_class='mdi mdi-plus-thick',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
), ),
PluginMenuButton( PluginMenuButton(
link='plugins:netbox_topology_views:coordinate_import', link='plugins:netbox_topology_views:coordinate_import',
title='Import', title=_('Import'),
icon_class='mdi mdi-upload', icon_class='mdi mdi-upload',
permissions=['netbox_topology_views.add_coordinate'] permissions=['netbox_topology_views.add_coordinate']
) )
) )
menu = PluginMenu( menu = PluginMenu(
label='Topology Views', label=_('Topology Views'),
icon_class="mdi mdi-sitemap", icon_class="mdi mdi-sitemap",
groups=( groups=(
('TOPOLOGY', (_('Topology'),
( (
PluginMenuItem(link="plugins:netbox_topology_views:home", link_text="Topology", permissions=["dcim.view_site", "dcim.view_device"]), PluginMenuItem(link="plugins:netbox_topology_views:home", link_text=_("Topology"), permissions=["dcim.view_site", "dcim.view_device"]),
), ),
), ),
('WEITERE ANSICHTEN', (_('More views'),
( (
PluginMenuItem(link="plugins:netbox_topology_views:rack_elevation", link_text="Rack-Ansicht", permissions=["dcim.view_rack", "dcim.view_device", "dcim.view_cable"]), PluginMenuItem(link="plugins:netbox_topology_views:rack_elevation", link_text=_("Rack view"), permissions=["dcim.view_rack", "dcim.view_device", "dcim.view_cable"]),
), ),
), ),
('COORDINATES', (_('Coordinates'),
( (
PluginMenuItem(link="plugins:netbox_topology_views:coordinategroup_list", link_text="Coordinate Groups", buttons=coordinategroup_buttons, permissions=['netbox_topology_views.view_coordinategroup']), PluginMenuItem(link="plugins:netbox_topology_views:coordinategroup_list", link_text=_("Coordinate Groups"), buttons=coordinategroup_buttons, permissions=['netbox_topology_views.view_coordinategroup']),
PluginMenuItem(link="plugins:netbox_topology_views:coordinate_list", link_text="Device Coordinates", buttons=coordinate_buttons, permissions=['netbox_topology_views.view_coordinate']), PluginMenuItem(link="plugins:netbox_topology_views:coordinate_list", link_text=_("Device Coordinates"), buttons=coordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:powerfeedcoordinate_list", link_text="Power Feed Coords", buttons=powerfeedcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']), PluginMenuItem(link="plugins:netbox_topology_views:powerfeedcoordinate_list", link_text=_("Power Feed Coords"), buttons=powerfeedcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:powerpanelcoordinate_list", link_text="Power Panel Coords", buttons=powerpanelcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']), PluginMenuItem(link="plugins:netbox_topology_views:powerpanelcoordinate_list", link_text=_("Power Panel Coords"), buttons=powerpanelcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
PluginMenuItem(link="plugins:netbox_topology_views:circuitcoordinate_list", link_text="Circuit Coordinates", buttons=circuitcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']), PluginMenuItem(link="plugins:netbox_topology_views:circuitcoordinate_list", link_text=_("Circuit Coordinates"), buttons=circuitcoordinate_buttons, permissions=['netbox_topology_views.view_coordinate']),
), ),
), ),
('PREFERENCES', (_('Preferences'),
( (
PluginMenuItem(link="plugins:netbox_topology_views:images", link_text="Images", permissions=[ "dcim.view_site","dcim.view_devicerole"]), PluginMenuItem(link="plugins:netbox_topology_views:images", link_text=_("Images"), permissions=[ "dcim.view_site","dcim.view_devicerole"]),
PluginMenuItem(link="plugins:netbox_topology_views:individualoptions", link_text="Individual Options", permissions=['netbox_topology_views.change_individualoptions']), PluginMenuItem(link="plugins:netbox_topology_views:individualoptions", link_text=_("Individual Options"), permissions=['netbox_topology_views.change_individualoptions']),
), ),
), ),
), ),
@@ -6,6 +6,8 @@
padding: 2px 6px; padding: 2px 6px;
font-size: .78rem; font-size: .78rem;
line-height: 1.15; line-height: 1.15;
background: #eef6ff;
color: #132238;
} }
.rack-device:hover { .rack-device:hover {
min-height: 2.8rem; min-height: 2.8rem;
@@ -13,10 +15,29 @@
z-index: 3; z-index: 3;
} }
.rack-device:hover span { white-space: normal; } .rack-device:hover span { white-space: normal; }
.rack-frame {
border-color: #718096;
background-color: #fff;
background-image: repeating-linear-gradient(to top, rgba(56, 73, 89, .16) 0, rgba(56, 73, 89, .16) 1px, transparent 1px, transparent calc(100% / var(--rack-units)));
}
.rack-device:hover { color: #132238; }
html[data-bs-theme="dark"] .rack-frame,
body[data-bs-theme="dark"] .rack-frame,
html[data-netbox-color-mode="dark"] .rack-frame {
border-color: #3b4654;
background-color: #212b36;
background-image: repeating-linear-gradient(to top, rgba(200, 215, 230, .14) 0, rgba(200, 215, 230, .14) 1px, transparent 1px, transparent calc(100% / var(--rack-units)));
}
html[data-bs-theme="dark"] .rack-device,
body[data-bs-theme="dark"] .rack-device,
html[data-netbox-color-mode="dark"] .rack-device {
background: #162e45;
color: #fff;
}
.rack-topology { .rack-topology {
position: relative; position: relative;
min-height: 18rem; min-height: 18rem;
overflow-x: auto; overflow: auto;
padding: 1rem; padding: 1rem;
background: var(--tblr-bg-surface-secondary, rgba(127, 127, 127, .05)); background: var(--tblr-bg-surface-secondary, rgba(127, 127, 127, .05));
} }
@@ -45,6 +66,7 @@
width: 15rem; width: 15rem;
} }
.rack-topology-column h4 { text-align: center; font-size: .85rem; } .rack-topology-column h4 { text-align: center; font-size: .85rem; }
.rack-topology-device-list { display: flex; flex-direction: column; gap: 40px; }
.rack-topology-node { .rack-topology-node {
display: block; display: block;
padding: .55rem .75rem; padding: .55rem .75rem;
@@ -78,12 +100,31 @@
transition: opacity .12s, stroke .12s, filter .12s, stroke-width .12s; transition: opacity .12s, stroke .12s, filter .12s, stroke-width .12s;
} }
.rack-topology-edge.is-highlighted { .rack-topology-edge.is-highlighted {
stroke: #fff !important; stroke: var(--topology-highlight-color, #16a34a) !important;
stroke-width: 5; stroke-width: 5;
opacity: 1; opacity: 1;
filter: drop-shadow(0 0 5px #fff); filter: drop-shadow(0 0 5px var(--topology-highlight-color, #16a34a));
} }
.rack-topology-edge.is-dimmed { opacity: .12; } .rack-topology-edge.is-dimmed { opacity: .12; }
.rack-topology-edge.is-wireless {
stroke-dasharray: 7 7;
stroke-linecap: round;
}
.rack-topology-edge.is-power {
stroke-dasharray: 2 4;
stroke-linecap: round;
}
#rack-topology-card:fullscreen {
margin: 0 !important;
border: 0;
border-radius: 0;
background: var(--tblr-bg-surface, #fff);
display: flex;
flex-direction: column;
overflow: hidden;
}
#rack-topology-card:fullscreen .card-body { min-height: 0; flex: 1; overflow: hidden; }
#rack-topology-card:fullscreen .rack-topology { height: calc(100vh - 5.5rem); }
.rack-topology-tooltip { .rack-topology-tooltip {
display: none; display: none;
position: absolute; position: absolute;
@@ -109,3 +150,10 @@
border-top: 1px solid var(--tblr-border-color, #ced4da); border-top: 1px solid var(--tblr-border-color, #ced4da);
} }
.rack-topology-tooltip small { opacity: .65; } .rack-topology-tooltip small { opacity: .65; }
.rack-cable-count {
min-width: 2rem;
margin-left: .35rem;
background-color: #52606d !important;
color: #fff !important;
text-align: center;
}
@@ -1 +1 @@
(()=>{var w=(o,t)=>()=>(o&&(t=o(o=0)),t);var f=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var l=(o,t,e)=>new Promise((r,s)=>{var c=n=>{try{a(e.next(n))}catch(i){s(i)}},g=n=>{try{a(e.throw(n))}catch(i){s(i)}},a=n=>n.done?r(n.value):Promise.resolve(n.value).then(c,g);a((e=e.apply(o,t)).next())});var u,d=w(()=>{u={success:o=>{let t=document.querySelector("#topology-plugin-success-toast");if(!t)return console.error("Could not find toast component!");let e=t.querySelector("span");e.textContent=o,new window.Toast(t).show()},error:o=>{let t=document.querySelector("#topology-plugin-error-toast");if(!t)return console.error("Could not find toast component!");let e=t.querySelector("span");e.textContent=o,new window.Toast(t).show()}}});var y=f(p=>{d();var m={};document.querySelector("form#images").addEventListener("submit",o=>l(null,null,function*(){o.preventDefault();try{let t=yield fetch("/"+basePath+"api/plugins/netbox_topology_views/images/save/",{method:"POST",body:JSON.stringify(m),headers:{"X-CSRFToken":window.CSRF_TOKEN,"Content-Type":"application/json"}});if(!t.ok)throw new Error(yield t.text());u.success("Saved settings")}catch(t){console.dir(t),u.error(t.message)}}));document.querySelectorAll("form#images .dropdown-menu img").forEach(o=>{o.addEventListener("click",t=>{var c;if(!(t.currentTarget instanceof HTMLElement))return;let{dataset:{role:e,image:r}}=t.currentTarget;m[e]=r;let s=(c=t.currentTarget.closest(".dropdown"))==null?void 0:c.querySelector(`#dropdownMenuButton${e}`);s&&(s.innerHTML=`<img src="${r}" />`)})})});y();})(); (()=>{var w=(o,t)=>()=>(o&&(t=o(o=0)),t);var f=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var l=(o,t,e)=>new Promise((r,s)=>{var c=n=>{try{a(e.next(n))}catch(i){s(i)}},g=n=>{try{a(e.throw(n))}catch(i){s(i)}},a=n=>n.done?r(n.value):Promise.resolve(n.value).then(c,g);a((e=e.apply(o,t)).next())});var u,d=w(()=>{u={success:o=>{let t=document.querySelector("#topology-plugin-success-toast");if(!t)return console.error("Could not find toast component!");let e=t.querySelector("span");e.textContent=o,new window.Toast(t).show()},error:o=>{let t=document.querySelector("#topology-plugin-error-toast");if(!t)return console.error("Could not find toast component!");let e=t.querySelector("span");e.textContent=o,new window.Toast(t).show()}}});var y=f(p=>{d();var m={};document.querySelector("form#images").addEventListener("submit",o=>l(null,null,function*(){o.preventDefault();try{let t=yield fetch("/"+basePath+"api/plugins/netbox_topology_views/images/save/",{method:"POST",body:JSON.stringify(m),headers:{"X-CSRFToken":window.CSRF_TOKEN,"Content-Type":"application/json"}});if(!t.ok)throw new Error(yield t.text());u.success(window.topologyI18n?.savedSettings??"Saved settings")}catch(t){console.dir(t),u.error(t.message)}}));document.querySelectorAll("form#images .dropdown-menu img").forEach(o=>{o.addEventListener("click",t=>{var c;if(!(t.currentTarget instanceof HTMLElement))return;let{dataset:{role:e,image:r}}=t.currentTarget;m[e]=r;let s=(c=t.currentTarget.closest(".dropdown"))==null?void 0:c.querySelector(`#dropdownMenuButton${e}`);s&&(s.innerHTML=`<img src="${r}" />`)})})});y();})();
+20 -3
View File
@@ -46,12 +46,12 @@ html[data-netbox-color-mode=dark] #visgraph {
.rack-frame { display: flex; height: calc(var(--rack-units) * 22px); min-height: 280px; border: 4px solid #3b4654; background: repeating-linear-gradient(to top, rgba(127,127,127,.14) 0, rgba(127,127,127,.14) 1px, transparent 1px, transparent calc(100% / var(--rack-units))); } .rack-frame { display: flex; height: calc(var(--rack-units) * 22px); min-height: 280px; border: 4px solid #3b4654; background: repeating-linear-gradient(to top, rgba(127,127,127,.14) 0, rgba(127,127,127,.14) 1px, transparent 1px, transparent calc(100% / var(--rack-units))); }
.rack-unit-labels { width: 2rem; display: flex; flex-direction: column; justify-content: space-around; font-size: .55rem; text-align: center; color: var(--tblr-secondary, #667382); } .rack-unit-labels { width: 2rem; display: flex; flex-direction: column; justify-content: space-around; font-size: .55rem; text-align: center; color: var(--tblr-secondary, #667382); }
.rack-device-area { position: relative; flex: 1; border-left: 1px solid #3b4654; } .rack-device-area { position: relative; flex: 1; border-left: 1px solid #3b4654; }
.rack-device { position: absolute; left: 3px; right: 3px; min-height: 2px; overflow: hidden; padding: 2px 6px; border: 2px solid #1685fc; border-radius: 3px; background: #162e45; color: #fff; font-size: .78rem; line-height: 1.15; text-decoration: none; } .rack-device { position: absolute; left: 3px; right: 3px; min-height: 2px; overflow: hidden; padding: 2px 6px; border: 2px solid #1685fc; border-radius: 3px; background: #eef6ff; color: #132238; font-size: .78rem; line-height: 1.15; text-decoration: none; }
.rack-device:hover { min-height: 2.8rem; overflow: visible; filter: brightness(1.25); color: #fff; z-index: 3; } .rack-device:hover { min-height: 2.8rem; overflow: visible; filter: brightness(1.25); color: #fff; z-index: 3; }
.rack-device:hover span { white-space: normal; } .rack-device:hover span { white-space: normal; }
.rack-device span, .rack-device small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .rack-device span, .rack-device small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rack-device small { font-size: .6rem; opacity: .8; } .rack-device small { font-size: .6rem; opacity: .8; }
.rack-topology { position: relative; min-height: 18rem; overflow-x: auto; padding: 1rem; background: var(--tblr-bg-surface-secondary, rgba(127,127,127,.05)); } .rack-topology { position: relative; min-height: 18rem; overflow: auto; padding: 1rem; background: var(--tblr-bg-surface-secondary, rgba(127,127,127,.05)); }
.rack-topology-lines { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; } .rack-topology-lines { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; }
.rack-topology-columns { position: relative; z-index: 2; display: flex; align-items: flex-start; justify-content: space-around; gap: 5rem; min-width: max-content; pointer-events: none; } .rack-topology-columns { position: relative; z-index: 2; display: flex; align-items: flex-start; justify-content: space-around; gap: 5rem; min-width: max-content; pointer-events: none; }
.rack-topology-column { display: flex; flex-direction: column; gap: .75rem; width: 15rem; } .rack-topology-column { display: flex; flex-direction: column; gap: .75rem; width: 15rem; }
@@ -62,7 +62,7 @@ html[data-netbox-color-mode=dark] #visgraph {
.rack-topology-node strong, .rack-topology-node small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .rack-topology-node strong, .rack-topology-node small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rack-topology-node small { opacity: .7; } .rack-topology-node small { opacity: .7; }
.rack-topology-edge { fill: none; stroke-width: 3; opacity: .8; pointer-events: stroke; cursor: pointer; transition: opacity .12s, stroke .12s, filter .12s, stroke-width .12s; } .rack-topology-edge { fill: none; stroke-width: 3; opacity: .8; pointer-events: stroke; cursor: pointer; transition: opacity .12s, stroke .12s, filter .12s, stroke-width .12s; }
.rack-topology-edge.is-highlighted { stroke: #fff !important; stroke-width: 5; opacity: 1; filter: drop-shadow(0 0 5px #fff); } .rack-topology-edge.is-highlighted { stroke: var(--topology-highlight-color, #16a34a) !important; stroke-width: 5; opacity: 1; filter: drop-shadow(0 0 5px var(--topology-highlight-color, #16a34a)); }
.rack-topology-edge.is-dimmed { opacity: .12; } .rack-topology-edge.is-dimmed { opacity: .12; }
.rack-topology-tooltip { display: none; position: absolute; z-index: 10; width: max-content; max-width: 28rem; padding: .65rem .8rem; border: 1px solid var(--tblr-border-color, #ced4da); border-radius: .35rem; background: var(--tblr-bg-surface, #fff); box-shadow: 0 4px 18px rgba(0,0,0,.25); pointer-events: none; } .rack-topology-tooltip { display: none; position: absolute; z-index: 10; width: max-content; max-width: 28rem; padding: .65rem .8rem; border: 1px solid var(--tblr-border-color, #ced4da); border-radius: .35rem; background: var(--tblr-bg-surface, #fff); box-shadow: 0 4px 18px rgba(0,0,0,.25); pointer-events: none; }
.rack-topology-tooltip.is-visible { display: block; } .rack-topology-tooltip.is-visible { display: block; }
@@ -70,6 +70,23 @@ html[data-netbox-color-mode=dark] #visgraph {
.rack-topology-tooltip ul { margin: .4rem 0 0; padding: 0; list-style: none; } .rack-topology-tooltip ul { margin: .4rem 0 0; padding: 0; list-style: none; }
.rack-topology-tooltip li + li { margin-top: .45rem; padding-top: .45rem; border-top: 1px solid var(--tblr-border-color, #ced4da); } .rack-topology-tooltip li + li { margin-top: .45rem; padding-top: .45rem; border-top: 1px solid var(--tblr-border-color, #ced4da); }
.rack-topology-tooltip small { opacity: .65; } .rack-topology-tooltip small { opacity: .65; }
.rack-cable-count { min-width: 2rem; margin-left: .35rem; background-color: #52606d !important; color: #fff !important; text-align: center; }
.rack-frame {
border-color: #718096;
background-color: #fff;
}
.rack-topology-device-list { display: flex; flex-direction: column; gap: 40px; }
.rack-topology-edge.is-wireless { stroke-dasharray: 7 7; stroke-linecap: round; }
#rack-topology-card:fullscreen { margin: 0 !important; border: 0; border-radius: 0; background: var(--tblr-bg-surface, #fff); display: flex; flex-direction: column; overflow: hidden; }
#rack-topology-card:fullscreen .card-body { min-height: 0; flex: 1; overflow: hidden; }
#rack-topology-card:fullscreen .rack-topology { height: calc(100vh - 5.5rem); }
html[data-bs-theme="dark"], body[data-bs-theme="dark"], html[data-netbox-color-mode="dark"] {
.rack-frame { border-color: #3b4654; background-color: #212b36; }
.rack-device { background: #162e45; color: #fff; }
}
@media (max-width: 700px) { @media (max-width: 700px) {
.rack-elevation-grid { grid-template-columns: 1fr; } .rack-elevation-grid { grid-template-columns: 1fr; }
@@ -15,7 +15,7 @@ document.querySelector('form#images').addEventListener('submit', async (e) => {
}) })
if (!res.ok) throw new Error(await res.text()) if (!res.ok) throw new Error(await res.text())
toast.success('Saved settings') toast.success(window.topologyI18n?.savedSettings ?? 'Saved settings')
} catch (err) { } catch (err) {
console.dir(err) console.dir(err)
toast.error(err.message) toast.error(err.message)
+2 -1
View File
@@ -1,4 +1,5 @@
import django_tables2 as tables import django_tables2 as tables
from django.utils.translation import gettext_lazy as _
from netbox.tables import NetBoxTable, ChoiceFieldColumn from netbox.tables import NetBoxTable, ChoiceFieldColumn
from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate from netbox_topology_views.models import CoordinateGroup, Coordinate, CircuitCoordinate, PowerPanelCoordinate, PowerFeedCoordinate
@@ -7,7 +8,7 @@ class CoordinateGroupListTable(NetBoxTable):
name = tables.Column( name = tables.Column(
linkify=True linkify=True
) )
devices = tables.Column() devices = tables.Column(verbose_name=_('Devices'))
class Meta(NetBoxTable.Meta): class Meta(NetBoxTable.Meta):
model = CoordinateGroup model = CoordinateGroup
@@ -1,32 +1,33 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}Topology Views Coordinates{% endblock title %} {% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
Coordinates {% trans "Coordinates" %}
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">Group</th> <th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Circuit</th> <th scope="row">{% trans "Circuit" %}</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">X-Coordinate</th> <th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Y-Coordinate</th> <th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add new Circuit Coordinates{% endblock title %} {% block title %}{% trans "Add new Circuit Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Circuit Coordinates{% endblock title %} {% block title %}{% trans "Edit Circuit Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Circuit Coordinates{% endblock title %} {% block title %}{% trans "Circuit Coordinates" %}{% endblock title %}
@@ -1,32 +1,33 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}Topology Views Coordinates{% endblock title %} {% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
Coordinates {% trans "Coordinates" %}
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">Group</th> <th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Device</th> <th scope="row">{% trans "Device" %}</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">X-Coordinate</th> <th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Y-Coordinate</th> <th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add new Device Coordinates{% endblock title %} {% block title %}{% trans "Add new Device Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Device Coordinates{% endblock title %} {% block title %}{% trans "Edit Device Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Device Coordinates{% endblock title %} {% block title %}{% trans "Device Coordinates" %}{% endblock title %}
@@ -1,25 +1,26 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% load render_table from django_tables2 %} {% load render_table from django_tables2 %}
{% block title %}Topology Views Coordinate Group{% endblock title %} {% block title %}{% trans "Topology Views Coordinate Group" %}{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
Coordinate Group {% trans "Coordinate Group" %}
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">Name</th> <th scope="row">{% trans "Name" %}</th>
<td>{{ object.name }}</td> <td>{{ object.name }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Description</th> <th scope="row">{% trans "Description" %}</th>
<td>{{ object.description|placeholder }}</td> <td>{{ object.description|placeholder }}</td>
</tr> </tr>
</table> </table>
@@ -35,7 +36,7 @@
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">Circuit Coordinates</h5> <h5 class="card-header">{% trans "Circuit Coordinates" %}</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table circuitcoordinates_table %} {% render_table circuitcoordinates_table %}
</div> </div>
@@ -43,7 +44,7 @@
</div> </div>
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">Power Panel Coordinates</h5> <h5 class="card-header">{% trans "Power Panel Coordinates" %}</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table powerpanelcoordinates_table %} {% render_table powerpanelcoordinates_table %}
</div> </div>
@@ -51,7 +52,7 @@
</div> </div>
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">Power Feed Coordinates</h5> <h5 class="card-header">{% trans "Power Feed Coordinates" %}</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table powerfeedcoordinates_table %} {% render_table powerfeedcoordinates_table %}
</div> </div>
@@ -59,7 +60,7 @@
</div> </div>
<div class="col col-md-12"> <div class="col col-md-12">
<div class="card"> <div class="card">
<h5 class="card-header">Device Coordinates</h5> <h5 class="card-header">{% trans "Device Coordinates" %}</h5>
<div class="card-body table-responsive"> <div class="card-body table-responsive">
{% render_table coordinates_table %} {% render_table coordinates_table %}
</div> </div>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add a new Coordinate Group{% endblock title %} {% block title %}{% trans "Add a new Coordinate Group" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Coordinate Group{% endblock title %} {% block title %}{% trans "Edit Coordinate Group" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Coordinate Groups{% endblock title %} {% block title %}{% trans "Coordinate Groups" %}{% endblock title %}
@@ -1,10 +1,11 @@
{% extends 'base/layout.html' %} {% extends 'base/layout.html' %}
{% load i18n %}
{% load buttons %} {% load buttons %}
{% load render_table from django_tables2 %} {% load render_table from django_tables2 %}
{% load helpers %} {% load helpers %}
{% load static %} {% load static %}
{% block title %}Topology Views Images{% endblock %} {% block title %}{% trans "Topology Views Images" %}{% endblock %}
{% block head %} {% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}"> <link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}">
@@ -20,7 +21,7 @@
{% if role.image %} {% if role.image %}
<img src="{{ role.image }}" /> <img src="{{ role.image }}" />
{% else %} {% else %}
Image {% trans "Image" %}
{% endif %} {% endif %}
</button> </button>
<div class="dropdown-menu mt-2" aria-labelledby="dropdownMenuButton{{ role.id }}"> <div class="dropdown-menu mt-2" aria-labelledby="dropdownMenuButton{{ role.id }}">
@@ -36,7 +37,7 @@
{% endfor %} {% endfor %}
</div> </div>
<button class="btn btn-primary" type="submit">Save</button> <button class="btn btn-primary" type="submit">{% trans "Save" %}</button>
</form> </form>
{% include 'netbox_topology_views/toasts.html' %} {% include 'netbox_topology_views/toasts.html' %}
{% endblock content %} {% endblock content %}
@@ -44,6 +45,7 @@
{% block javascript %} {% block javascript %}
<script type="text/javascript"> <script type="text/javascript">
const basePath = '{{ basepath }}'; const basePath = '{{ basepath }}';
window.topologyI18n = {savedSettings: '{{ _("Saved settings")|escapejs }}'};
</script> </script>
<script src="{% static 'netbox_topology_views/js/images.js' %}" defer></script> <script src="{% static 'netbox_topology_views/js/images.js' %}" defer></script>
{% endblock javascript %} {% endblock javascript %}
@@ -1,11 +1,12 @@
{% extends 'generic/_base.html' %} {% extends 'generic/_base.html' %}
{% load i18n %}
{% load buttons %} {% load buttons %}
{% load render_table from django_tables2 %} {% load render_table from django_tables2 %}
{% load static %} {% load static %}
{% load perms %} {% load perms %}
{% load helpers %} {% load helpers %}
{% block title %}Topology Views{% endblock %} {% block title %}{% trans "Topology Views" %}{% endblock %}
{% block head %} {% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/vendor.css' %}"> <link rel="stylesheet" href="{% static 'netbox_topology_views/css/vendor.css' %}">
@@ -18,11 +19,11 @@
{% block extra_controls %}{% endblock %} {% block extra_controls %}{% endblock %}
<a id="btnDownloadXml" class="btn btn-info" href="#"> <a id="btnDownloadXml" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i> <i class="mdi mdi-download"></i>
Download XML {% trans "Download XML" %}
</a> </a>
<a id="btnDownloadImage" class="btn btn-info" href="#"> <a id="btnDownloadImage" class="btn btn-info" href="#">
<i class="mdi mdi-download"></i> <i class="mdi mdi-download"></i>
Download PNG {% trans "Download PNG" %}
</a> </a>
</div> </div>
</div> </div>
@@ -33,13 +34,13 @@
{% block tab_items %} {% block tab_items %}
<li class="nav-item" role="presentation"> <li class="nav-item" role="presentation">
<button class="nav-link active" id="network-tab" data-bs-toggle="tab" data-bs-target="#networks" type="button" role="tab" aria-controls="filters-form" aria-selected="true"> <button class="nav-link active" id="network-tab" data-bs-toggle="tab" data-bs-target="#networks" type="button" role="tab" aria-controls="filters-form" aria-selected="true">
Network {% trans "Network" %}
</button> </button>
</li> </li>
{% if filter_form %} {% if filter_form %}
<li class="nav-item" role="presentation"> <li class="nav-item" role="presentation">
<button class="nav-link" id="filters-form-tab" data-bs-toggle="tab" data-bs-target="#filters-form" type="button" role="tab" aria-controls="object-list" aria-selected="false"> <button class="nav-link" id="filters-form-tab" data-bs-toggle="tab" data-bs-target="#filters-form" type="button" role="tab" aria-controls="object-list" aria-selected="false">
Filters {% trans "Filters" %}
{% if filter_form %}{% badge filter_form.changed_data|length bg_color="blue" %}{% endif %} {% if filter_form %}{% badge filter_form.changed_data|length bg_color="blue" %}{% endif %}
</button> </button>
</li> </li>
@@ -62,11 +63,11 @@
<div class="tab-pane show active" id="networks" role="tabpanel" aria-labelledby="network-tab"> <div class="tab-pane show active" id="networks" role="tabpanel" aria-labelledby="network-tab">
<div class="panel-body"> <div class="panel-body">
{% if filter_required %} {% if filter_required %}
<div class="bg-warning text-white p-2">Nothing to display! Set filters and hit search button or set "Draw Default Layout" in your individual options.</div> <div class="bg-warning text-white p-2">{% trans 'Nothing to display! Set filters and hit search button or set "Draw Default Layout" in your individual options.' %}</div>
{% endif %} {% endif %}
{% if empty_result %} {% if empty_result %}
<div class="bg-warning text-white p-2">Empty result set! Please review your filter settings.</div> <div class="bg-warning text-white p-2">{% trans "Empty result set! Please review your filter settings." %}</div>
<div class="bg-info text-white p-2">Hint: Some options may produce an empty result. Use at least "Show Unconnected/Cables/Logical Connections".</div> <div class="bg-info text-white p-2">{% trans 'Hint: Some options may produce an empty result. Use at least "Show Unconnected/Cables/Logical Connections".' %}</div>
{% endif %} {% endif %}
<div id="visgraph"></div> <div id="visgraph"></div>
</div> </div>
@@ -1,5 +1,6 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Topology Views Individual Options{% endblock %} {% block title %}{% trans "Topology Views Individual Options" %}{% endblock %}
{% block tabs %} {% endblock tabs %} {% block tabs %} {% endblock tabs %}
@@ -1,4 +1,5 @@
<a role="button" class="btn btn-primary" title="Topology" href="#" hx-get="/plugins/netbox_topology_views/topology/?location_id={{ object.id }}&show_cables=True&show_unconnected=True" hx-target="#htmx-modal-content" data-bs-toggle="modal" data-bs-target="#htmx-modal"> {% load i18n %}
<a role="button" class="btn btn-primary" title="{% trans "Topology" %}" href="#" hx-get="/plugins/netbox_topology_views/topology/?location_id={{ object.id }}&show_cables=True&show_unconnected=True" hx-target="#htmx-modal-content" data-bs-toggle="modal" data-bs-target="#htmx-modal">
<i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i> <i class="mdi mdi-transit-connection-variant" aria-hidden="true"></i>
Topology {% trans "Topology" %}
</a> </a>
@@ -1,32 +1,33 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}Topology Views Coordinates{% endblock title %} {% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
Coordinates {% trans "Coordinates" %}
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">Group</th> <th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Power Feed</th> <th scope="row">{% trans "Power Feed" %}</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">X-Coordinate</th> <th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Y-Coordinate</th> <th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add new Power Feed Coordinates{% endblock title %} {% block title %}{% trans "Add new Power Feed Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Power Feed Coordinates{% endblock title %} {% block title %}{% trans "Edit Power Feed Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Power Feed Coordinates{% endblock title %} {% block title %}{% trans "Power Feed Coordinates" %}{% endblock title %}
@@ -1,32 +1,33 @@
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% block title %}Topology Views Coordinates{% endblock title %} {% block title %}{% trans "Topology Views Coordinates" %}{% endblock title %}
{% block content %} {% block content %}
<div class="row mb-3"> <div class="row mb-3">
<div class="col col-md-6"> <div class="col col-md-6">
<div class="card"> <div class="card">
<h5 class="card-header"> <h5 class="card-header">
Coordinates {% trans "Coordinates" %}
</h5> </h5>
<div class="card-body"> <div class="card-body">
<table class="table table-hover attr-table"> <table class="table table-hover attr-table">
<tr> <tr>
<th scope="row">Group</th> <th scope="row">{% trans "Group" %}</th>
<td>{{ object.group|linkify }}</td> <td>{{ object.group|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Power Panel</th> <th scope="row">{% trans "Power Panel" %}</th>
<td>{{ object.device|linkify }}</td> <td>{{ object.device|linkify }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">X-Coordinate</th> <th scope="row">{% trans "X-Coordinate" %}</th>
<td>{{ object.x }}</td> <td>{{ object.x }}</td>
</tr> </tr>
<tr> <tr>
<th scope="row">Y-Coordinate</th> <th scope="row">{% trans "Y-Coordinate" %}</th>
<td>{{ object.y }}</td> <td>{{ object.y }}</td>
</tr> </tr>
</table> </table>
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Add new Power Panel Coordinates{% endblock title %} {% block title %}{% trans "Add new Power Panel Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_edit.html' %} {% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block title %}Edit Power Panel Coordinates{% endblock title %} {% block title %}{% trans "Edit Power Panel Coordinates" %}{% endblock title %}
@@ -1,3 +1,4 @@
{% extends 'generic/object_list.html' %} {% extends 'generic/object_list.html' %}
{% load i18n %}
{% block title %}Power Panel Coordinates{% endblock title %} {% block title %}{% trans "Power Panel Coordinates" %}{% endblock title %}
@@ -1,8 +1,9 @@
{% extends 'generic/_base.html' %} {% extends 'generic/_base.html' %}
{% load helpers %} {% load helpers %}
{% load i18n %}
{% load static %} {% load static %}
{% block title %}Rack-Ansicht{% endblock %} {% block title %}{% trans "Rack view" %}{% endblock %}
{% block head %} {% block head %}
<link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}"> <link rel="stylesheet" href="{% static 'netbox_topology_views/css/app.css' %}">
@@ -11,7 +12,7 @@
{% block content %} {% block content %}
<div class="card mb-3"> <div class="card mb-3">
<div class="card-header"><strong>Racks auswählen</strong></div> <div class="card-header"><strong>{% trans "Select racks" %}</strong></div>
<div class="card-body"> <div class="card-body">
<form method="get"> <form method="get">
<div class="row g-3"> <div class="row g-3">
@@ -25,8 +26,8 @@
{% endfor %} {% endfor %}
</div> </div>
<div class="mt-3"> <div class="mt-3">
<button class="btn btn-primary" type="submit"><i class="mdi mdi-magnify"></i> Anzeigen</button> <button class="btn btn-primary" type="submit"><i class="mdi mdi-magnify"></i> {% trans "Show" %}</button>
<a class="btn btn-outline-secondary" href="{% url 'plugins:netbox_topology_views:rack_elevation' %}">Zurücksetzen</a> <a class="btn btn-outline-secondary" href="{% url 'plugins:netbox_topology_views:rack_elevation' %}">{% trans "Reset" %}</a>
</div> </div>
</form> </form>
</div> </div>
@@ -34,18 +35,18 @@
{% if racks %} {% if racks %}
<div class="d-flex justify-content-end align-items-center gap-2 mb-3 flex-wrap"> <div class="d-flex justify-content-end align-items-center gap-2 mb-3 flex-wrap">
<strong class="me-2">Alle Racks exportieren:</strong> <strong class="me-2">{% trans "Export all racks:" %}</strong>
<button class="btn btn-sm btn-outline-primary rack-export" data-format="svg" data-scope="all">SVG</button> <button class="btn btn-sm btn-outline-primary rack-export" data-format="svg" data-scope="all">SVG</button>
<button class="btn btn-sm btn-outline-primary rack-export" data-format="png" data-scope="all">PNG</button> <button class="btn btn-sm btn-outline-primary rack-export" data-format="png" data-scope="all">PNG</button>
<button class="btn btn-sm btn-outline-primary rack-export" data-format="drawio" data-scope="all">draw.io</button> <button class="btn btn-sm btn-outline-primary rack-export" data-format="drawio" data-scope="all">draw.io</button>
</div> </div>
<div class="rack-elevation-grid"> <div class="rack-elevation-grid">
{% for rack in racks %} {% for rack in racks %}
<section class="rack-card"> <section class="rack-card" data-rack-id="{{ rack.pk }}" data-rack-units="{{ rack.u_height }}">
<header> <header>
<div><a href="{{ rack.get_absolute_url }}"><strong>{{ rack.name }}</strong></a><br> <div><a href="{{ rack.get_absolute_url }}"><strong>{{ rack.name }}</strong></a><br>
<small>{{ rack.site }}{% if rack.location %} · {{ rack.location }}{% endif %} · {{ rack.u_height }}U</small></div> <small>{{ rack.site }}{% if rack.location %} · {{ rack.location }}{% endif %} · {{ rack.u_height }}U</small></div>
<div class="btn-group" aria-label="{{ rack.name }} exportieren"> <div class="btn-group" aria-label="{% blocktrans with name=rack.name %}Export {{ name }}{% endblocktrans %}">
<button class="btn btn-sm btn-outline-secondary rack-export" data-format="svg" data-scope="{{ rack.pk }}">SVG</button> <button class="btn btn-sm btn-outline-secondary rack-export" data-format="svg" data-scope="{{ rack.pk }}">SVG</button>
<button class="btn btn-sm btn-outline-secondary rack-export" data-format="png" data-scope="{{ rack.pk }}">PNG</button> <button class="btn btn-sm btn-outline-secondary rack-export" data-format="png" data-scope="{{ rack.pk }}">PNG</button>
<button class="btn btn-sm btn-outline-secondary rack-export" data-format="drawio" data-scope="{{ rack.pk }}">draw.io</button> <button class="btn btn-sm btn-outline-secondary rack-export" data-format="drawio" data-scope="{{ rack.pk }}">draw.io</button>
@@ -63,6 +64,9 @@
{% for device in rack.elevation_devices %} {% for device in rack.elevation_devices %}
{% if device.elevation_face == face %} {% if device.elevation_face == face %}
<a class="rack-device" href="{{ device.get_absolute_url }}" <a class="rack-device" href="{{ device.get_absolute_url }}"
data-face="{{ face }}" data-device-name="{{ device.name|default:device.device_type.model }}"
data-device-type="{{ device.device_type }}" data-position="{{ device.position|default:1 }}"
data-device-height="{{ device.device_type.u_height|default:1 }}" data-device-color="#{{ device.role.color|default:'1685fc' }}"
style="bottom: {{ device.elevation_bottom }}%; height: {{ device.elevation_height }}%; border-color: #{{ device.role.color }}" style="bottom: {{ device.elevation_bottom }}%; height: {{ device.elevation_height }}%; border-color: #{{ device.role.color }}"
title="{{ device.name }} · {{ device.device_type }} · U{{ device.position }}"> title="{{ device.name }} · {{ device.device_type }} · U{{ device.position }}">
<span>{{ device.name|default:device.device_type.model }}</span> <span>{{ device.name|default:device.device_type.model }}</span>
@@ -79,22 +83,40 @@
{% endfor %} {% endfor %}
</div> </div>
<div class="card mt-4"> <div id="rack-topology-card" class="card mt-4">
<div class="card-header d-flex justify-content-between align-items-center"> <div class="card-header d-flex justify-content-between align-items-center">
<strong>Kabeltopologie</strong> <strong>{% trans "Cable topology" %}</strong>
<div class="d-flex gap-2"> <div class="d-flex gap-2 align-items-center">
<div class="d-flex gap-3 align-items-center rack-topology-kind-toggles">
<div class="form-check form-check-inline mb-0">
<input class="form-check-input" type="checkbox" id="rack-topology-show-wireless" checked>
<label class="form-check-label" for="rack-topology-show-wireless">{% trans "Wireless/WLAN" %}</label>
</div>
<div class="form-check form-check-inline mb-0">
<input class="form-check-input" type="checkbox" id="rack-topology-show-power" checked>
<label class="form-check-label" for="rack-topology-show-power">{% trans "Power" %}</label>
</div>
</div>
<div class="btn-group"> <div class="btn-group">
<button class="btn btn-sm btn-outline-primary topology-export" data-format="svg">SVG</button> <button class="btn btn-sm btn-outline-primary topology-export" data-format="svg">SVG</button>
<button class="btn btn-sm btn-outline-primary topology-export" data-format="png">PNG</button> <button class="btn btn-sm btn-outline-primary topology-export" data-format="png">PNG</button>
<button class="btn btn-sm btn-outline-primary topology-export" data-format="drawio">draw.io</button> <button class="btn btn-sm btn-outline-primary topology-export" data-format="drawio">draw.io</button>
</div> </div>
<div class="btn-group" aria-label="{% trans "Zoom topology" %}">
<button id="rack-topology-zoom-out" class="btn btn-sm btn-outline-secondary" type="button" title="{% trans "Zoom out" %}"><i class="mdi mdi-minus"></i></button>
<button id="rack-topology-zoom-reset" class="btn btn-sm btn-outline-secondary" type="button" title="{% trans "Reset zoom" %}"><span id="rack-topology-zoom-label">100%</span></button>
<button id="rack-topology-zoom-in" class="btn btn-sm btn-outline-secondary" type="button" title="{% trans "Zoom in" %}"><i class="mdi mdi-plus"></i></button>
</div>
<button id="rack-topology-reset" class="btn btn-sm btn-outline-secondary" type="button"> <button id="rack-topology-reset" class="btn btn-sm btn-outline-secondary" type="button">
<i class="mdi mdi-restore"></i> Positionen zurücksetzen <i class="mdi mdi-restore"></i> {% trans "Reset positions" %}
</button>
<button id="rack-topology-fullscreen" class="btn btn-sm btn-outline-secondary" type="button">
<i class="mdi mdi-fullscreen"></i> {% trans "Full screen" %}
</button> </button>
</div> </div>
</div> </div>
<div class="card-body"> <div class="card-body">
<div id="rack-topology" class="rack-topology" aria-label="Topologie der ausgewählten Racks"> <div id="rack-topology" class="rack-topology" aria-label="{% trans "Topology of the selected racks" %}">
<svg class="rack-topology-lines" aria-hidden="true"></svg> <svg class="rack-topology-lines" aria-hidden="true"></svg>
<div class="rack-topology-columns"></div> <div class="rack-topology-columns"></div>
<div class="rack-topology-tooltip" role="tooltip"></div> <div class="rack-topology-tooltip" role="tooltip"></div>
@@ -103,12 +125,13 @@
</div> </div>
{{ rack_topology|json_script:"rack-topology-data" }} {{ rack_topology|json_script:"rack-topology-data" }}
{{ rack_export|json_script:"rack-export-data" }} {{ rack_export|json_script:"rack-export-data" }}
{{ i18n|json_script:"rack-i18n-data" }}
<div class="card mt-4"> <div class="card mt-4">
<div class="card-header"><strong>Verkabelung der angezeigten Racks</strong> <span class="badge bg-secondary">{{ cables|length }}</span></div> <div class="card-header"><strong>{% trans "Cabling of the displayed racks" %}</strong> <span class="badge rack-cable-count">{{ cables|length }}</span></div>
<div class="table-responsive"> <div class="table-responsive">
<table class="table table-hover mb-0"> <table class="table table-hover mb-0">
<thead><tr><th>Kabel</th><th>A-Seite</th><th>B-Seite</th><th>Typ</th><th>Status</th></tr></thead> <thead><tr><th>{% trans "Cable" %}</th><th>{% trans "A side" %}</th><th>{% trans "B side" %}</th><th>{% trans "Type" %}</th><th>{% trans "Status" %}</th></tr></thead>
<tbody> <tbody>
{% for row in cables %} {% for row in cables %}
<tr> <tr>
@@ -117,15 +140,15 @@
<td>{% if row.b %}<strong>{{ row.b.device_name }}</strong><br><small>{{ row.b.name }}</small>{% else %}—{% endif %}</td> <td>{% if row.b %}<strong>{{ row.b.device_name }}</strong><br><small>{{ row.b.name }}</small>{% else %}—{% endif %}</td>
<td>{{ row.cable.type|default:'—' }}</td><td>{{ row.cable.get_status_display }}</td> <td>{{ row.cable.type|default:'—' }}</td><td>{{ row.cable.get_status_display }}</td>
</tr> </tr>
{% empty %}<tr><td colspan="5" class="text-muted text-center py-4">Keine Verkabelung gefunden.</td></tr>{% endfor %} {% empty %}<tr><td colspan="5" class="text-muted text-center py-4">{% trans "No cabling found." %}</td></tr>{% endfor %}
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
{% elif has_selection %} {% elif has_selection %}
<div class="alert alert-warning">Für diese Auswahl wurden keine belegten Racks gefunden. Aktiviere „Leere Racks einschließen“, um auch leere Racks zu sehen.</div> <div class="alert alert-warning">{% trans "No occupied racks were found for this selection. Enable “Include empty racks” to show empty racks as well." %}</div>
{% else %} {% else %}
<div class="alert alert-info">Wähle ein oder mehrere Racks oder grenze die Ansicht über Standort und Location ein.</div> <div class="alert alert-info">{% trans "Select one or more racks, or narrow the view by site and location." %}</div>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
@@ -136,43 +159,110 @@
const source = document.getElementById('rack-topology-data'); const source = document.getElementById('rack-topology-data');
if (!root || !source) return; if (!root || !source) return;
const data = JSON.parse(source.textContent); const data = JSON.parse(source.textContent);
const t = JSON.parse(document.getElementById('rack-i18n-data').textContent);
const isWirelessEdge = edge => edge.kind === 'wireless' || edge.kind === 'wireless-lan';
const isPowerEdge = edge => edge.kind === 'power';
const showWirelessCheckbox = document.getElementById('rack-topology-show-wireless');
const showPowerCheckbox = document.getElementById('rack-topology-show-power');
const isEdgeVisible = edge => {
if (isWirelessEdge(edge)) return showWirelessCheckbox ? showWirelessCheckbox.checked : true;
if (isPowerEdge(edge)) return showPowerCheckbox ? showPowerCheckbox.checked : true;
return true;
};
const applyKindVisibility = () => {
const showWireless = showWirelessCheckbox ? showWirelessCheckbox.checked : true;
root.querySelectorAll('.rack-topology-node').forEach(node => {
if (node.dataset.kind === 'wireless-lan') {
node.style.display = showWireless ? '' : 'none';
}
});
drawEdges();
};
const rackData = JSON.parse(document.getElementById('rack-export-data').textContent); const rackData = JSON.parse(document.getElementById('rack-export-data').textContent);
const columns = root.querySelector('.rack-topology-columns'); const columns = root.querySelector('.rack-topology-columns');
const svg = root.querySelector('svg'); const svg = root.querySelector('svg');
const tooltip = root.querySelector('.rack-topology-tooltip'); const tooltip = root.querySelector('.rack-topology-tooltip');
const resetButton = document.getElementById('rack-topology-reset'); const resetButton = document.getElementById('rack-topology-reset');
const storageKey = `netbox-rack-topology:${window.location.pathname}${window.location.search}`; const fullscreenButton = document.getElementById('rack-topology-fullscreen');
const topologyCard = document.getElementById('rack-topology-card');
const zoomInButton = document.getElementById('rack-topology-zoom-in');
const zoomOutButton = document.getElementById('rack-topology-zoom-out');
const zoomResetButton = document.getElementById('rack-topology-zoom-reset');
const zoomLabel = document.getElementById('rack-topology-zoom-label');
let topologyZoom = 1;
const activeNetBoxTheme = () => {
for (const element of [topologyCard, document.body, document.documentElement]) {
const match = getComputedStyle(element).backgroundColor.match(/[\d.]+/g);
if (match && match.length >= 3 && (match.length < 4 || Number(match[3]) > 0)) {
const [red, green, blue] = match.map(Number);
return (.2126 * red + .7152 * green + .0722 * blue) < 140 ? 'dark' : 'light';
}
}
return document.body.dataset.bsTheme || document.documentElement.dataset.bsTheme || 'light';
};
const topologyHighlightColor = () => activeNetBoxTheme() === 'dark' ? '#ffffff' : '#16a34a';
const applyTopologyTheme = () => {
root.style.setProperty('--topology-highlight-color', topologyHighlightColor());
root.querySelectorAll('.rack-topology-edge.is-highlighted').forEach(path => {
path.style.setProperty('stroke', topologyHighlightColor(), 'important');
path.style.setProperty('filter', `drop-shadow(0 0 5px ${topologyHighlightColor()})`, 'important');
});
};
applyTopologyTheme();
const topologyThemeObserver = new MutationObserver(() => requestAnimationFrame(applyTopologyTheme));
topologyThemeObserver.observe(document.body, {attributes: true, attributeFilter: ['data-bs-theme']});
topologyThemeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-bs-theme', 'data-netbox-color-mode'],
});
const storageKey = `netbox-rack-topology-v3:${window.location.pathname}${window.location.search}`;
let storedPositions = {}; let storedPositions = {};
try { storedPositions = JSON.parse(localStorage.getItem(storageKey) || '{}'); } catch (_) {} try { storedPositions = JSON.parse(localStorage.getItem(storageKey) || '{}'); } catch (_) {}
const groups = new Map(); const groups = new Map();
data.nodes.forEach(node => { data.nodes.forEach(node => {
const groupName = node.rack_name || 'Extern'; const groupKey = node.rack_id ? `rack-${node.rack_id}` : `external-${node.rack_name || t.external}`;
if (!groups.has(groupName)) groups.set(groupName, []); if (!groups.has(groupKey)) groups.set(groupKey, {
groups.get(groupName).push(node); name: node.rack_name || t.external,
rackUnits: node.rack_u_height || null,
descUnits: Boolean(node.rack_desc_units),
nodes: [],
});
groups.get(groupKey).nodes.push(node);
}); });
groups.forEach((nodes, name) => { groups.forEach(group => {
const column = document.createElement('section'); const column = document.createElement('section');
column.className = 'rack-topology-column'; column.className = 'rack-topology-column';
const heading = document.createElement('h4'); const heading = document.createElement('h4');
heading.textContent = name; heading.textContent = group.name;
column.appendChild(heading); column.appendChild(heading);
nodes.forEach(node => { const nodeContainer = document.createElement('div');
nodeContainer.className = 'rack-topology-device-list';
nodeContainer.style.display = 'flex';
nodeContainer.style.flexDirection = 'column';
nodeContainer.style.gap = '20px';
nodeContainer.style.rowGap = '20px';
column.appendChild(nodeContainer);
group.nodes.sort((a, b) => group.descUnits
? (a.position || 0) - (b.position || 0)
: (b.position || 0) - (a.position || 0)
).forEach(node => {
const item = document.createElement(node.url ? 'a' : 'div'); const item = document.createElement(node.url ? 'a' : 'div');
item.className = 'rack-topology-node'; item.className = 'rack-topology-node';
item.id = `topology-${node.node_id}`; item.id = `topology-${node.node_id}`;
item.style.setProperty('--node-color', `#${node.color}`); item.style.setProperty('--node-color', `#${node.color}`);
item.dataset.nodeId = node.node_id; item.dataset.nodeId = node.node_id;
if (node.kind) item.dataset.kind = node.kind;
if (node.url) item.href = node.url; if (node.url) item.href = node.url;
const nameElement = document.createElement('strong'); const nameElement = document.createElement('strong');
nameElement.textContent = node.device_name; nameElement.textContent = node.device_name;
const portElement = document.createElement('small'); const portElement = document.createElement('small');
portElement.textContent = node.name; portElement.textContent = node.subtitle || node.name;
item.append(nameElement, portElement); item.append(nameElement, portElement);
const saved = storedPositions[node.node_id]; const saved = storedPositions[node.node_id];
if (saved) item.style.transform = `translate(${saved.x}px, ${saved.y}px)`; if (saved) item.style.transform = `translate(${saved.x}px, ${saved.y}px)`;
column.appendChild(item); nodeContainer.appendChild(item);
}); });
columns.appendChild(column); columns.appendChild(column);
}); });
@@ -191,29 +281,42 @@
element.textContent = value == null ? '—' : String(value); element.textContent = value == null ? '—' : String(value);
return element.innerHTML; return element.innerHTML;
}; };
const setEdgeHighlighted = (path, highlighted) => {
path.classList.toggle('is-highlighted', highlighted);
if (highlighted) {
path.style.setProperty('stroke', topologyHighlightColor(), 'important');
path.style.setProperty('filter', `drop-shadow(0 0 5px ${topologyHighlightColor()})`, 'important');
} else {
path.style.removeProperty('stroke');
path.style.removeProperty('filter');
}
};
const drawEdges = () => { const drawEdges = () => {
const bounds = root.getBoundingClientRect(); const bounds = root.getBoundingClientRect();
let width = Math.max(root.clientWidth, columns.scrollWidth + 32); let width = Math.max(root.clientWidth, columns.scrollWidth * topologyZoom + 32);
let height = Math.max(root.clientHeight, columns.scrollHeight + 32); let height = Math.max(root.clientHeight, columns.scrollHeight * topologyZoom + 32);
svg.style.width = `${width}px`; svg.style.width = `${width}px`;
svg.style.height = `${height}px`; svg.style.height = `${height}px`;
svg.setAttribute('viewBox', `0 0 ${width} ${height}`); svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
svg.replaceChildren(); svg.replaceChildren();
data.edges.forEach(edge => { data.edges.forEach(edge => {
if (!isEdgeVisible(edge)) return;
const from = document.getElementById(`topology-${edge.from}`); const from = document.getElementById(`topology-${edge.from}`);
const to = document.getElementById(`topology-${edge.to}`); const to = document.getElementById(`topology-${edge.to}`);
if (!from || !to) return; if (!from || !to) return;
const a = from.getBoundingClientRect(), b = to.getBoundingClientRect(); const a = from.getBoundingClientRect(), b = to.getBoundingClientRect();
const x1 = a.left + a.width / 2 - bounds.left; const x1 = a.left + a.width / 2 - bounds.left + root.scrollLeft;
const y1 = a.top + a.height / 2 - bounds.top; const y1 = a.top + a.height / 2 - bounds.top + root.scrollTop;
const x2 = b.left + b.width / 2 - bounds.left; const x2 = b.left + b.width / 2 - bounds.left + root.scrollLeft;
const y2 = b.top + b.height / 2 - bounds.top; const y2 = b.top + b.height / 2 - bounds.top + root.scrollTop;
const bend = Math.max(30, Math.abs(x2 - x1) * .35); const bend = Math.max(30, Math.abs(x2 - x1) * .35);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', `M ${x1} ${y1} C ${x1 + bend} ${y1}, ${x2 - bend} ${y2}, ${x2} ${y2}`); path.setAttribute('d', `M ${x1} ${y1} C ${x1 + bend} ${y1}, ${x2 - bend} ${y2}, ${x2} ${y2}`);
path.setAttribute('stroke', edge.color); path.setAttribute('stroke', edge.color);
path.classList.add('rack-topology-edge'); path.classList.add('rack-topology-edge');
if (isWirelessEdge(edge)) path.classList.add('is-wireless');
if (isPowerEdge(edge)) path.classList.add('is-power');
path.dataset.from = edge.from; path.dataset.from = edge.from;
path.dataset.to = edge.to; path.dataset.to = edge.to;
const title = document.createElementNS('http://www.w3.org/2000/svg', 'title'); const title = document.createElementNS('http://www.w3.org/2000/svg', 'title');
@@ -221,42 +324,46 @@
path.appendChild(title); path.appendChild(title);
if (edge.url) path.addEventListener('click', () => window.location.href = edge.url); if (edge.url) path.addEventListener('click', () => window.location.href = edge.url);
path.addEventListener('mouseenter', event => { path.addEventListener('mouseenter', event => {
path.classList.add('is-highlighted'); setEdgeHighlighted(path, true);
showTooltip( showTooltip(
`<strong>${escapeHtml(edge.label)}</strong>` + `<strong>${isWirelessEdge(edge) ? 'WLAN · ' : isPowerEdge(edge) ? `${t.power} · ` : ''}${escapeHtml(edge.label)}</strong>` +
`<span>${escapeHtml(edge.from_device)} · ${escapeHtml(edge.from_port)}</span>` + `<span>${escapeHtml(edge.from_device)} · ${escapeHtml(edge.from_port)}</span>` +
`<span>↔ ${escapeHtml(edge.to_device)} · ${escapeHtml(edge.to_port)}</span>`, `<span>↔ ${escapeHtml(edge.to_device)} · ${escapeHtml(edge.to_port)}</span>`,
event.target event.target
); );
}); });
path.addEventListener('mouseleave', () => { path.addEventListener('mouseleave', () => {
path.classList.remove('is-highlighted'); setEdgeHighlighted(path, false);
hideTooltip(); hideTooltip();
}); });
svg.appendChild(path); svg.appendChild(path);
}); });
}; };
const connectedEdges = nodeId => data.edges.filter(edge => edge.from === nodeId || edge.to === nodeId); const connectedEdges = nodeId => data.edges.filter(edge => isEdgeVisible(edge) && (edge.from === nodeId || edge.to === nodeId));
root.querySelectorAll('.rack-topology-node').forEach(node => { root.querySelectorAll('.rack-topology-node').forEach(node => {
const nodeId = node.dataset.nodeId; const nodeId = node.dataset.nodeId;
node.addEventListener('mouseenter', () => { node.addEventListener('mouseenter', () => {
const connections = connectedEdges(nodeId); const connections = connectedEdges(nodeId);
svg.querySelectorAll('.rack-topology-edge').forEach(path => { svg.querySelectorAll('.rack-topology-edge').forEach(path => {
path.classList.toggle('is-highlighted', path.dataset.from === nodeId || path.dataset.to === nodeId); const connected = path.dataset.from === nodeId || path.dataset.to === nodeId;
path.classList.toggle('is-dimmed', path.dataset.from !== nodeId && path.dataset.to !== nodeId); setEdgeHighlighted(path, connected);
path.classList.toggle('is-dimmed', !connected);
}); });
const rows = connections.map(edge => { const rows = connections.map(edge => {
const outgoing = edge.from === nodeId; const outgoing = edge.from === nodeId;
const localPort = outgoing ? edge.from_port : edge.to_port; const localPort = outgoing ? edge.from_port : edge.to_port;
const remoteDevice = outgoing ? edge.to_device : edge.from_device; const remoteDevice = outgoing ? edge.to_device : edge.from_device;
const remotePort = outgoing ? edge.to_port : edge.from_port; const remotePort = outgoing ? edge.to_port : edge.from_port;
return `<li><strong>${escapeHtml(localPort)}</strong><span>→ ${escapeHtml(remoteDevice)} · ${escapeHtml(remotePort)}</span><small>${escapeHtml(edge.label)}</small></li>`; return `<li><strong>${escapeHtml(localPort)}</strong><span>→ ${escapeHtml(remoteDevice)} · ${escapeHtml(remotePort)}</span><small>${isWirelessEdge(edge) ? 'WLAN · ' : isPowerEdge(edge) ? `${t.power} · ` : ''}${escapeHtml(edge.label)}</small></li>`;
}).join(''); }).join('');
showTooltip(`<strong>Verbindungen (${connections.length})</strong><ul>${rows || '<li>Keine Verbindungen</li>'}</ul>`, node); showTooltip(`<strong>${escapeHtml(t.connections)} (${connections.length})</strong><ul>${rows || `<li>${escapeHtml(t.noConnections)}</li>`}</ul>`, node);
}); });
node.addEventListener('mouseleave', () => { node.addEventListener('mouseleave', () => {
svg.querySelectorAll('.rack-topology-edge').forEach(path => path.classList.remove('is-highlighted', 'is-dimmed')); svg.querySelectorAll('.rack-topology-edge').forEach(path => {
setEdgeHighlighted(path, false);
path.classList.remove('is-dimmed');
});
hideTooltip(); hideTooltip();
}); });
@@ -271,8 +378,8 @@
}); });
node.addEventListener('pointermove', event => { node.addEventListener('pointermove', event => {
if (!drag) return; if (!drag) return;
const x = drag.x + event.clientX - drag.startX; const x = drag.x + (event.clientX - drag.startX) / topologyZoom;
const y = drag.y + event.clientY - drag.startY; const y = drag.y + (event.clientY - drag.startY) / topologyZoom;
drag.moved ||= Math.abs(x - drag.x) > 3 || Math.abs(y - drag.y) > 3; drag.moved ||= Math.abs(x - drag.x) > 3 || Math.abs(y - drag.y) > 3;
node.style.transform = `translate(${x}px, ${y}px)`; node.style.transform = `translate(${x}px, ${y}px)`;
storedPositions[nodeId] = {x, y}; storedPositions[nodeId] = {x, y};
@@ -301,15 +408,112 @@
root.querySelectorAll('.rack-topology-node').forEach(node => node.style.transform = ''); root.querySelectorAll('.rack-topology-node').forEach(node => node.style.transform = '');
drawEdges(); drawEdges();
}); });
fullscreenButton?.addEventListener('click', async () => {
if (document.fullscreenElement === topologyCard) await document.exitFullscreen();
else await topologyCard.requestFullscreen();
});
document.addEventListener('fullscreenchange', () => {
const active = document.fullscreenElement === topologyCard;
fullscreenButton.innerHTML = active
? `<i class="mdi mdi-fullscreen-exit"></i> ${escapeHtml(t.exitFullScreen)}`
: `<i class="mdi mdi-fullscreen"></i> ${escapeHtml(t.fullScreen)}`;
requestAnimationFrame(drawEdges);
});
const setTopologyZoom = value => {
topologyZoom = Math.min(2, Math.max(.5, Math.round(value * 10) / 10));
columns.style.zoom = topologyZoom;
zoomLabel.textContent = `${Math.round(topologyZoom * 100)}%`;
requestAnimationFrame(drawEdges);
};
zoomInButton?.addEventListener('click', () => setTopologyZoom(topologyZoom + .1));
zoomOutButton?.addEventListener('click', () => setTopologyZoom(topologyZoom - .1));
zoomResetButton?.addEventListener('click', () => setTopologyZoom(1));
const xmlEscape = value => String(value ?? '').replace(/[&<>"']/g, char => ({ const xmlEscape = value => String(value ?? '').replace(/[&<>"']/g, char => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;'
})[char]); })[char]);
const safeName = value => String(value || 'export').replace(/[^a-z0-9._-]+/gi, '-').replace(/^-|-$/g, ''); const safeName = value => String(value || 'export').replace(/[^a-z0-9._-]+/gi, '-').replace(/^-|-$/g, '');
const exportPalette = () => {
const declaredTheme = activeNetBoxTheme();
const dark = declaredTheme === 'dark' || (!declaredTheme && window.matchMedia('(prefers-color-scheme: dark)').matches);
return dark ? {
frame: '#52606d', grid: '#667382', heading: '#8fc8ff', muted: '#a9b7c6',
deviceFill: '#162e45', deviceText: '#ffffff', deviceSubtext: '#cad5df',
} : {
frame: '#718096', grid: '#8b99a8', heading: '#0b69b7', muted: '#52606d',
deviceFill: '#eef6ff', deviceText: '#132238', deviceSubtext: '#52606d',
};
};
const svgDocument = (width, height, content) => const svgDocument = (width, height, content) =>
`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${content}</svg>`; `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${content}</svg>`;
const drawioDocument = cells =>
`<mxfile host="app.diagrams.net" type="device"><diagram name="Rack export"><mxGraphModel page="0" background="none" grid="1" guides="1" connect="1"><root><mxCell id="0"/><mxCell id="1" parent="0"/>${cells}</root></mxGraphModel></diagram></mxfile>`;
const renderedRackData = racks => racks.map(rack => {
const card = document.querySelector(`.rack-card[data-rack-id="${rack.id}"]`);
if (!card) return rack;
const rackUnits = Number.parseFloat(card.dataset.rackUnits) || rack.u_height || 1;
const devices = Array.from(card.querySelectorAll('.rack-device')).map(device => {
const bottom = Number.parseFloat(device.style.bottom) || 0;
const height = Number.parseFloat(device.style.height) || (100 / rackUnits);
const deviceHeight = Math.max(height / 100 * rackUnits, 1);
const bottomUnits = bottom / 100 * rackUnits;
const startingUnit = Number(rack.starting_unit) || 1;
return {
name: device.dataset.deviceName || device.querySelector('span')?.textContent || t.device,
type: device.dataset.deviceType || '',
position: rack.desc_units
? startingUnit + rackUnits - deviceHeight - bottomUnits
: startingUnit + bottomUnits,
height: deviceHeight,
face: device.dataset.face === 'rear' ? 'rear' : 'front',
color: device.dataset.deviceColor || '#1685fc',
};
});
return {...rack, devices};
});
const buildRackDrawio = racks => {
const palette = exportPalette();
const unit = 22, faceWidth = 250, labelWidth = 28, faceGap = 28, rackGap = 44, header = 55;
const rackWidth = labelWidth + faceWidth * 2 + faceGap;
let cells = '', cellId = 2;
const vertex = (value, style, x, y, width, height) => {
const id = cellId++;
cells += `<mxCell id="${id}" value="${xmlEscape(value)}" style="${style}" vertex="1" parent="1"><mxGeometry x="${x}" y="${y}" width="${width}" height="${height}" as="geometry"/></mxCell>`;
return id;
};
racks.forEach((rack, rackIndex) => {
const baseX = 10 + rackIndex * (rackWidth + rackGap);
const rackHeight = rack.u_height * unit;
const startingUnit = Number(rack.starting_unit) || 1;
vertex(rack.name, `text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;fontSize=16;fontStyle=1;fontColor=${palette.heading};`, baseX, 0, rackWidth, 25);
vertex(`${rack.site}${rack.location ? ` · ${rack.location}` : ''} · ${rack.u_height}U`, `text;html=1;strokeColor=none;fillColor=none;align=left;fontSize=10;fontColor=${palette.muted};`, baseX, 24, rackWidth, 20);
['front', 'rear'].forEach((face, faceIndex) => {
const x = baseX + labelWidth + faceIndex * (faceWidth + faceGap);
vertex(face === 'front' ? t.front.toUpperCase() : t.rear.toUpperCase(), `text;html=1;strokeColor=none;fillColor=none;align=center;fontSize=10;fontColor=${palette.muted};`, x, 38, faceWidth, 17);
vertex('', `rounded=0;html=1;fillColor=none;strokeColor=${palette.frame};strokeWidth=4;`, x, header, faceWidth, rackHeight);
for (let row = 0; row < rack.u_height; row++) {
const y = header + row * unit;
const unitLabel = rack.desc_units ? startingUnit + row : startingUnit + rack.u_height - 1 - row;
if (faceIndex === 0) vertex(String(unitLabel), `text;html=1;strokeColor=none;fillColor=none;align=right;fontSize=8;fontColor=${palette.muted};`, x - labelWidth, y, labelWidth - 4, unit);
}
rack.devices.filter(device => device.face === face).forEach(device => {
const positionOffset = device.position - startingUnit;
const y = rack.desc_units
? header + positionOffset * unit
: header + rackHeight - (positionOffset + device.height) * unit;
const h = Math.max(device.height * unit, 4);
const value = h >= 31 ? `${device.name}<br><font style="font-size:9px">U${device.position} · ${device.type}</font>` : device.name;
vertex(value, `rounded=1;html=1;whiteSpace=wrap;overflow=hidden;align=left;verticalAlign=top;spacingLeft=5;spacingTop=2;fillColor=${palette.deviceFill};strokeColor=${device.color};strokeWidth=2;fontColor=${palette.deviceText};fontSize=11;`, x + 3, y + 1, faceWidth - 6, h - 2);
});
});
});
return drawioDocument(cells);
};
const buildRackSvg = racks => { const buildRackSvg = racks => {
const palette = exportPalette();
const unit = 22, faceWidth = 250, labelWidth = 28, faceGap = 28, rackGap = 44, header = 55; const unit = 22, faceWidth = 250, labelWidth = 28, faceGap = 28, rackGap = 44, header = 55;
const rackWidth = labelWidth + faceWidth * 2 + faceGap; const rackWidth = labelWidth + faceWidth * 2 + faceGap;
const maxUnits = Math.max(...racks.map(rack => rack.u_height || 1), 1); const maxUnits = Math.max(...racks.map(rack => rack.u_height || 1), 1);
@@ -319,36 +523,53 @@
racks.forEach((rack, rackIndex) => { racks.forEach((rack, rackIndex) => {
const baseX = 10 + rackIndex * (rackWidth + rackGap); const baseX = 10 + rackIndex * (rackWidth + rackGap);
const rackHeight = rack.u_height * unit; const rackHeight = rack.u_height * unit;
content += `<text x="${baseX}" y="20" fill="#1685fc" font-family="sans-serif" font-size="16" font-weight="700">${xmlEscape(rack.name)}</text>`; const startingUnit = Number(rack.starting_unit) || 1;
content += `<text x="${baseX}" y="39" fill="#778899" font-family="sans-serif" font-size="11">${xmlEscape(rack.site)}${rack.location ? ` · ${xmlEscape(rack.location)}` : ''} · ${rack.u_height}U</text>`; content += `<text x="${baseX}" y="20" fill="${palette.heading}" font-family="sans-serif" font-size="16" font-weight="700">${xmlEscape(rack.name)}</text>`;
content += `<text x="${baseX}" y="39" fill="${palette.muted}" font-family="sans-serif" font-size="11">${xmlEscape(rack.site)}${rack.location ? ` · ${xmlEscape(rack.location)}` : ''} · ${rack.u_height}U</text>`;
['front', 'rear'].forEach((face, faceIndex) => { ['front', 'rear'].forEach((face, faceIndex) => {
const x = baseX + labelWidth + faceIndex * (faceWidth + faceGap); const x = baseX + labelWidth + faceIndex * (faceWidth + faceGap);
content += `<text x="${x + faceWidth / 2}" y="51" text-anchor="middle" fill="#778899" font-family="sans-serif" font-size="10">${face === 'front' ? 'VORDERSEITE' : 'RÜCKSEITE'}</text>`; content += `<text x="${x + faceWidth / 2}" y="51" text-anchor="middle" fill="${palette.muted}" font-family="sans-serif" font-size="10">${face === 'front' ? t.front.toUpperCase() : t.rear.toUpperCase()}</text>`;
content += `<rect x="${x}" y="${header}" width="${faceWidth}" height="${rackHeight}" fill="none" stroke="#52606d" stroke-width="4"/>`; content += `<rect x="${x}" y="${header}" width="${faceWidth}" height="${rackHeight}" fill="none" stroke="${palette.frame}" stroke-width="4"/>`;
for (let u = 1; u <= rack.u_height; u++) { for (let row = 0; row < rack.u_height; row++) {
const y = header + rackHeight - u * unit; const y = header + row * unit;
content += `<line x1="${x}" y1="${y}" x2="${x + faceWidth}" y2="${y}" stroke="#667382" stroke-opacity=".35"/>`; const unitLabel = rack.desc_units ? startingUnit + row : startingUnit + rack.u_height - 1 - row;
if (faceIndex === 0) content += `<text x="${x - 6}" y="${y + 15}" text-anchor="end" fill="#778899" font-family="sans-serif" font-size="9">${u}</text>`; content += `<line x1="${x}" y1="${y}" x2="${x + faceWidth}" y2="${y}" stroke="${palette.grid}" stroke-opacity=".35"/>`;
if (faceIndex === 0) content += `<text x="${x - 6}" y="${y + 15}" text-anchor="end" fill="${palette.muted}" font-family="sans-serif" font-size="9">${unitLabel}</text>`;
} }
rack.devices.filter(device => device.face === face).forEach(device => { rack.devices.filter(device => device.face === face).forEach(device => {
const y = header + rackHeight - (device.position - 1 + device.height) * unit; const positionOffset = device.position - startingUnit;
const y = rack.desc_units
? header + positionOffset * unit
: header + rackHeight - (positionOffset + device.height) * unit;
const h = Math.max(device.height * unit, 4); const h = Math.max(device.height * unit, 4);
content += `<rect x="${x + 3}" y="${y + 1}" width="${faceWidth - 6}" height="${h - 2}" rx="3" fill="#162e45" stroke="${xmlEscape(device.color)}" stroke-width="2"/>`; content += `<rect x="${x + 3}" y="${y + 1}" width="${faceWidth - 6}" height="${h - 2}" rx="3" fill="${palette.deviceFill}" stroke="${xmlEscape(device.color)}" stroke-width="2"/>`;
if (h >= 13) content += `<text x="${x + 9}" y="${y + Math.min(15, h - 4)}" fill="#fff" font-family="sans-serif" font-size="11" font-weight="600">${xmlEscape(device.name.slice(0, 34))}</text>`; if (h >= 13) content += `<text x="${x + 9}" y="${y + Math.min(15, h - 4)}" fill="${palette.deviceText}" font-family="sans-serif" font-size="11" font-weight="600">${xmlEscape(device.name.slice(0, 34))}</text>`;
if (h >= 31) content += `<text x="${x + 9}" y="${y + 28}" fill="#cad5df" font-family="sans-serif" font-size="9">U${device.position} · ${xmlEscape(device.type.slice(0, 34))}</text>`; if (h >= 31) content += `<text x="${x + 9}" y="${y + 28}" fill="${palette.deviceSubtext}" font-family="sans-serif" font-size="9">U${device.position} · ${xmlEscape(device.type.slice(0, 34))}</text>`;
}); });
}); });
}); });
return {svg: svgDocument(width, height, content), width, height}; return {svg: svgDocument(width, height, content), drawio: buildRackDrawio(racks), width, height};
}; };
const buildTopologySvg = () => { const buildTopologySvg = () => {
const palette = exportPalette();
const rootBounds = root.getBoundingClientRect(); const rootBounds = root.getBoundingClientRect();
let width = Math.max(root.clientWidth, columns.scrollWidth + 32); let width = Math.max(root.clientWidth, columns.scrollWidth * topologyZoom + 32);
let height = Math.max(root.clientHeight, columns.scrollHeight + 32); let height = Math.max(root.clientHeight, columns.scrollHeight * topologyZoom + 32);
const positions = new Map(); const positions = new Map();
const nodeCells = new Map();
let content = ''; let content = '';
let drawioCells = '', drawioId = 2;
root.querySelectorAll('.rack-topology-column').forEach(column => {
const heading = column.querySelector('h4');
const headingBounds = heading.getBoundingClientRect();
const headingX = headingBounds.left - rootBounds.left + root.scrollLeft;
const headingY = headingBounds.top - rootBounds.top + root.scrollTop;
content += `<text x="${headingX + headingBounds.width / 2}" y="${headingY + 15}" text-anchor="middle" fill="${palette.heading}" font-family="sans-serif" font-size="13" font-weight="600">${xmlEscape(heading.textContent)}</text>`;
drawioCells += `<mxCell id="group-${drawioId++}" value="${xmlEscape(heading.textContent)}" style="text;html=1;strokeColor=none;fillColor=none;align=center;fontStyle=1;fontColor=${palette.heading};" vertex="1" parent="1"><mxGeometry x="${headingX}" y="${headingY}" width="${headingBounds.width}" height="22" as="geometry"/></mxCell>`;
});
root.querySelectorAll('.rack-topology-node').forEach(node => { root.querySelectorAll('.rack-topology-node').forEach(node => {
if (node.style.display === 'none') return;
const bounds = node.getBoundingClientRect(); const bounds = node.getBoundingClientRect();
const x = bounds.left - rootBounds.left + root.scrollLeft; const x = bounds.left - rootBounds.left + root.scrollLeft;
const y = bounds.top - rootBounds.top + root.scrollTop; const y = bounds.top - rootBounds.top + root.scrollTop;
@@ -356,18 +577,28 @@
height = Math.max(height, y + bounds.height + 20); height = Math.max(height, y + bounds.height + 20);
positions.set(node.dataset.nodeId, {x: x + bounds.width / 2, y: y + bounds.height / 2}); positions.set(node.dataset.nodeId, {x: x + bounds.width / 2, y: y + bounds.height / 2});
const color = getComputedStyle(node).getPropertyValue('--node-color').trim() || '#1685fc'; const color = getComputedStyle(node).getPropertyValue('--node-color').trim() || '#1685fc';
content += `<rect x="${x}" y="${y}" width="${bounds.width}" height="${bounds.height}" rx="6" fill="#162e45" stroke="${xmlEscape(color)}" stroke-width="2"/>`; const cellId = `node-${drawioId++}`;
content += `<text x="${x + 10}" y="${y + 20}" fill="#fff" font-family="sans-serif" font-size="12" font-weight="600">${xmlEscape(node.querySelector('strong').textContent)}</text>`; nodeCells.set(node.dataset.nodeId, cellId);
content += `<text x="${x + 10}" y="${y + 37}" fill="#cad5df" font-family="sans-serif" font-size="9">${xmlEscape(node.querySelector('small').textContent)}</text>`; drawioCells += `<mxCell id="${cellId}" value="${xmlEscape(node.querySelector('strong').textContent)}&lt;br&gt;&lt;font style=&quot;font-size:9px&quot;&gt;${xmlEscape(node.querySelector('small').textContent)}&lt;/font&gt;" style="rounded=1;html=1;whiteSpace=wrap;align=left;verticalAlign=middle;spacingLeft=8;fillColor=${palette.deviceFill};strokeColor=${xmlEscape(color)};strokeWidth=2;fontColor=${palette.deviceText};fontSize=12;" vertex="1" parent="1"><mxGeometry x="${x}" y="${y}" width="${bounds.width}" height="${bounds.height}" as="geometry"/></mxCell>`;
content += `<rect x="${x}" y="${y}" width="${bounds.width}" height="${bounds.height}" rx="6" fill="${palette.deviceFill}" stroke="${xmlEscape(color)}" stroke-width="2"/>`;
content += `<text x="${x + 10}" y="${y + 20}" fill="${palette.deviceText}" font-family="sans-serif" font-size="12" font-weight="600">${xmlEscape(node.querySelector('strong').textContent)}</text>`;
content += `<text x="${x + 10}" y="${y + 37}" fill="${palette.deviceSubtext}" font-family="sans-serif" font-size="9">${xmlEscape(node.querySelector('small').textContent)}</text>`;
}); });
let edgeContent = ''; let edgeContent = '';
data.edges.forEach(edge => { data.edges.forEach(edge => {
if (!isEdgeVisible(edge)) return;
const a = positions.get(edge.from), b = positions.get(edge.to); const a = positions.get(edge.from), b = positions.get(edge.to);
if (!a || !b) return; if (!a || !b) return;
const bend = Math.max(30, Math.abs(b.x - a.x) * .35); const bend = Math.max(30, Math.abs(b.x - a.x) * .35);
edgeContent += `<path d="M ${a.x} ${a.y} C ${a.x + bend} ${a.y}, ${b.x - bend} ${b.y}, ${b.x} ${b.y}" fill="none" stroke="${xmlEscape(edge.color)}" stroke-width="3"/>`; const dashPattern = isWirelessEdge(edge) ? '7 7' : isPowerEdge(edge) ? '2 4' : null;
const edgeLabelPrefix = isWirelessEdge(edge) ? 'WLAN · ' : isPowerEdge(edge) ? `${t.power} · ` : '';
edgeContent += `<path d="M ${a.x} ${a.y} C ${a.x + bend} ${a.y}, ${b.x - bend} ${b.y}, ${b.x} ${b.y}" fill="none" stroke="${xmlEscape(edge.color)}" stroke-width="3"${dashPattern ? ` stroke-dasharray="${dashPattern}"` : ''}/>`;
const sourceId = nodeCells.get(edge.from), targetId = nodeCells.get(edge.to);
if (sourceId && targetId) {
drawioCells += `<mxCell id="edge-${drawioId++}" value="${xmlEscape(`${edgeLabelPrefix}${edge.label}`)}" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;endArrow=none;endFill=0;strokeColor=${xmlEscape(edge.color)};strokeWidth=2;fontSize=9;${dashPattern ? `dashed=1;dashPattern=${dashPattern};` : ''}" edge="1" parent="1" source="${sourceId}" target="${targetId}"><mxGeometry relative="1" as="geometry"/></mxCell>`;
}
}); });
return {svg: svgDocument(width, height, edgeContent + content), width, height}; return {svg: svgDocument(width, height, edgeContent + content), drawio: drawioDocument(drawioCells), width, height};
}; };
const downloadBlob = (blob, filename) => { const downloadBlob = (blob, filename) => {
@@ -377,7 +608,8 @@
link.click(); link.click();
setTimeout(() => URL.revokeObjectURL(link.href), 1000); setTimeout(() => URL.revokeObjectURL(link.href), 1000);
}; };
const asDrawio = ({svg, width, height}) => { const asDrawio = ({svg, drawio, width, height}) => {
if (drawio) return drawio;
const image = `data:image/svg+xml,${encodeURIComponent(svg)}`; const image = `data:image/svg+xml,${encodeURIComponent(svg)}`;
return `<mxfile host="app.diagrams.net" type="device"><diagram name="Rack export"><mxGraphModel page="0" background="none"><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="" style="shape=image;imageAspect=0;aspect=fixed;image=${xmlEscape(image)};" vertex="1" parent="1"><mxGeometry x="0" y="0" width="${width}" height="${height}" as="geometry"/></mxCell></root></mxGraphModel></diagram></mxfile>`; return `<mxfile host="app.diagrams.net" type="device"><diagram name="Rack export"><mxGraphModel page="0" background="none"><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="2" value="" style="shape=image;imageAspect=0;aspect=fixed;image=${xmlEscape(image)};" vertex="1" parent="1"><mxGeometry x="0" y="0" width="${width}" height="${height}" as="geometry"/></mxCell></root></mxGraphModel></diagram></mxfile>`;
}; };
@@ -406,15 +638,19 @@
}; };
document.querySelectorAll('.rack-export').forEach(button => button.addEventListener('click', () => { document.querySelectorAll('.rack-export').forEach(button => button.addEventListener('click', () => {
const racks = button.dataset.scope === 'all' ? rackData : rackData.filter(rack => String(rack.id) === button.dataset.scope); const selectedRacks = button.dataset.scope === 'all' ? rackData : rackData.filter(rack => String(rack.id) === button.dataset.scope);
const name = button.dataset.scope === 'all' ? 'racks-gesamt' : `rack-${safeName(racks[0]?.name)}`; const racks = renderedRackData(selectedRacks);
const name = button.dataset.scope === 'all' ? 'racks-all' : `rack-${safeName(racks[0]?.name)}`;
exportGraphic(buildRackSvg(racks), button.dataset.format, name); exportGraphic(buildRackSvg(racks), button.dataset.format, name);
})); }));
document.querySelectorAll('.topology-export').forEach(button => button.addEventListener('click', () => { document.querySelectorAll('.topology-export').forEach(button => button.addEventListener('click', () => {
exportGraphic(buildTopologySvg(), button.dataset.format, 'rack-topologie'); exportGraphic(buildTopologySvg(), button.dataset.format, 'rack-topology');
})); }));
requestAnimationFrame(drawEdges); showWirelessCheckbox?.addEventListener('change', applyKindVisibility);
showPowerCheckbox?.addEventListener('change', applyKindVisibility);
requestAnimationFrame(applyKindVisibility);
window.addEventListener('resize', drawEdges); window.addEventListener('resize', drawEdges);
root.addEventListener('scroll', drawEdges, {passive: true});
})(); })();
</script> </script>
{% endblock %} {% endblock %}
@@ -1,3 +1,4 @@
{% load i18n %}
<div id="django-messages" class="toast-container"> <div id="django-messages" class="toast-container">
<div <div
id="topology-plugin-error-toast" id="topology-plugin-error-toast"
@@ -10,13 +11,13 @@
<div class="d-flex"> <div class="d-flex">
<div class="toast-body"> <div class="toast-body">
😢 😢
<span>Error</span> <span>{% trans "Error" %}</span>
</div> </div>
<button <button
type="button" type="button"
class="btn-close me-2 m-auto" class="btn-close me-2 m-auto"
data-bs-dismiss="toast" data-bs-dismiss="toast"
aria-label="Close" aria-label="{% trans "Close" %}"
></button> ></button>
</div> </div>
</div> </div>
@@ -31,13 +32,13 @@
<div class="d-flex"> <div class="d-flex">
<div class="toast-body"> <div class="toast-body">
👍 👍
<span>Success</span> <span>{% trans "Success" %}</span>
</div> </div>
<button <button
type="button" type="button"
class="btn-close me-2 m-auto" class="btn-close me-2 m-auto"
data-bs-dismiss="toast" data-bs-dismiss="toast"
aria-label="Close" aria-label="{% trans "Close" %}"
></button> ></button>
</div> </div>
</div> </div>
+5 -5
View File
@@ -12,6 +12,7 @@ from django.db.models import Model
from django.templatetags.static import static from django.templatetags.static import static
from django.utils.text import camel_case_to_spaces, re_camel_case from django.utils.text import camel_case_to_spaces, re_camel_case
from django.contrib import messages from django.contrib import messages
from django.utils.translation import gettext as _
IMAGE_DIR = Path(settings.STATIC_ROOT) / "netbox_topology_views/img" IMAGE_DIR = Path(settings.STATIC_ROOT) / "netbox_topology_views/img"
if sys.version_info >= (3,9,0): if sys.version_info >= (3,9,0):
@@ -29,9 +30,8 @@ else:
def image_static_url(path: Path) -> str: def image_static_url(path: Path) -> str:
return static( # No leading slash: static file finders (e.g. the debug toolbar's) reject absolute paths.
f"/{path.relative_to(Path(settings.STATIC_ROOT))}" return static(path.relative_to(Path(settings.STATIC_ROOT)).as_posix())
)
def get_image_from_url(url: str) -> str: def get_image_from_url(url: str) -> str:
@@ -118,7 +118,7 @@ def get_query_settings(request):
# General options overrides # General options overrides
if save_coords == True and settings.PLUGINS_CONFIG["netbox_topology_views"]["allow_coordinates_saving"] == False: if save_coords == True and settings.PLUGINS_CONFIG["netbox_topology_views"]["allow_coordinates_saving"] == False:
save_coords = False save_coords = False
messages.warning(request, "Coordinate saving not allowed. Setting has been overridden") messages.warning(request, _("Coordinate saving not allowed. Setting has been overridden"))
elif settings.PLUGINS_CONFIG["netbox_topology_views"]["always_save_coordinates"] == True: elif settings.PLUGINS_CONFIG["netbox_topology_views"]["always_save_coordinates"] == True:
save_coords = True save_coords = True
@@ -344,7 +344,7 @@ def export_data_to_xml(data: dict):
if noPositionX > 0: if noPositionX > 0:
mxcell = doc.createElement('mxCell') mxcell = doc.createElement('mxCell')
mxcell.setAttribute('id', 'noPositionWarning') mxcell.setAttribute('id', 'noPositionWarning')
mxcell.setAttribute('value', 'One or more icons are misplaced. This happens if no coordinates are stored for a device. Turn on coordinates saving and make sure to drag all icons in the topology to a specific position before exporting to XML.') mxcell.setAttribute('value', _('One or more icons are misplaced. This happens if no coordinates are stored for a device. Turn on coordinates saving and make sure to drag all icons in the topology to a specific position before exporting to XML.'))
mxcell.setAttribute('style', 'text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;fontStyle=0;fontSize=35;labelBackgroundColor=#FFFF99;labelBorderColor=none;strokeWidth=20;') mxcell.setAttribute('style', 'text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;fontStyle=0;fontSize=35;labelBackgroundColor=#FFFF99;labelBorderColor=none;strokeWidth=20;')
mxcell.setAttribute('vertex', '1') mxcell.setAttribute('vertex', '1')
mxcell.setAttribute('parent', '1') mxcell.setAttribute('parent', '1')
+142 -40
View File
@@ -4,6 +4,7 @@ from typing import DefaultDict, Dict, Optional, Union
from itertools import chain from itertools import chain
from circuits.models import Circuit, CircuitTermination, ProviderNetwork from circuits.models import Circuit, CircuitTermination, ProviderNetwork
from dcim.choices import CableTypeChoices
from dcim.models import ( from dcim.models import (
Cable, Cable,
CableTermination, CableTermination,
@@ -25,9 +26,10 @@ from django.db.models import Q, QuerySet, Count
from django.db.models.functions import Lower from django.db.models.functions import Lower
from django.http import HttpRequest, HttpResponseRedirect, QueryDict from django.http import HttpRequest, HttpResponseRedirect, QueryDict
from django.shortcuts import render, get_object_or_404 from django.shortcuts import render, get_object_or_404
from django.utils.translation import gettext as _
from django.views.generic import View from django.views.generic import View
from extras.models import Tag, SavedFilter from extras.models import Tag, SavedFilter
from wireless.models import WirelessLink from wireless.models import WirelessLAN, WirelessLink
from netbox.views.generic import ( from netbox.views.generic import (
ObjectView, ObjectView,
ObjectListView, ObjectListView,
@@ -111,20 +113,20 @@ def create_node(
if device.provider is not None: if device.provider is not None:
node_content += ( node_content += (
f"<tr><th>Provider: </th><td>{device.provider.name}</td></tr>" f"<tr><th>{_('Provider')}: </th><td>{device.provider.name}</td></tr>"
) )
if device.type is not None: if device.type is not None:
node_content += f"<tr><th>Type: </th><td>{device.type.name}</td></tr>" node_content += f"<tr><th>{_('Type')}: </th><td>{device.type.name}</td></tr>"
elif isinstance(device, PowerPanel): elif isinstance(device, PowerPanel):
dev_name = device.name dev_name = device.name
node["id"] = f"p{device.pk}" node["id"] = f"p{device.pk}"
model_name = 'PowerPanelCoordinate' model_name = 'PowerPanelCoordinate'
if device.site is not None: if device.site is not None:
node_content += f"<tr><th>Site: </th><td>{device.site.name}</td></tr>" node_content += f"<tr><th>{_('Site')}: </th><td>{device.site.name}</td></tr>"
if device.location is not None: if device.location is not None:
node_content += ( node_content += (
f"<tr><th>Location: </th><td>{device.location.name}</td></tr>" f"<tr><th>{_('Location')}: </th><td>{device.location.name}</td></tr>"
) )
elif isinstance(device, PowerFeed): elif isinstance(device, PowerFeed):
dev_name = device.name dev_name = device.name
@@ -133,18 +135,18 @@ def create_node(
if device.power_panel is not None: if device.power_panel is not None:
node_content += ( node_content += (
f"<tr><th>Power Panel: </th><td>{device.power_panel.name}</td></tr>" f"<tr><th>{_('Power Panel')}: </th><td>{device.power_panel.name}</td></tr>"
) )
if device.type is not None: if device.type is not None:
node_content += f"<tr><th>Type: </th><td>{device.type}</td></tr>" node_content += f"<tr><th>{_('Type')}: </th><td>{device.type}</td></tr>"
if device.supply is not None: if device.supply is not None:
node_content += f"<tr><th>Supply: </th><td>{device.supply}</td></tr>" node_content += f"<tr><th>{_('Supply')}: </th><td>{device.supply}</td></tr>"
if device.phase is not None: if device.phase is not None:
node_content += f"<tr><th>Phase: </th><td>{device.phase}</td></tr>" node_content += f"<tr><th>{_('Phase')}: </th><td>{device.phase}</td></tr>"
if device.amperage is not None: if device.amperage is not None:
node_content += f"<tr><th>Amperage: </th><td>{device.amperage}</td></tr>" node_content += f"<tr><th>{_('Amperage')}: </th><td>{device.amperage}</td></tr>"
if device.voltage is not None: if device.voltage is not None:
node_content += f"<tr><th>Voltage: </th><td>{device.voltage}</td></tr>" node_content += f"<tr><th>{_('Voltage')}: </th><td>{device.voltage}</td></tr>"
else: else:
model_name = 'Coordinate' model_name = 'Coordinate'
dev_name = device.name dev_name = device.name
@@ -153,32 +155,32 @@ def create_node(
if device.device_type is not None: if device.device_type is not None:
node_content += ( node_content += (
f"<tr><th>Type: </th><td>{device.device_type.model}</td></tr>" f"<tr><th>{_('Type')}: </th><td>{device.device_type.model}</td></tr>"
) )
if device.role.name is not None: if device.role.name is not None:
node_content += ( node_content += (
f"<tr><th>Role: </th><td>{device.role.name}</td></tr>" f"<tr><th>{_('Role')}: </th><td>{device.role.name}</td></tr>"
) )
if device.serial != "": if device.serial != "":
node_content += f"<tr><th>Serial: </th><td>{device.serial}</td></tr>" node_content += f"<tr><th>{_('Serial')}: </th><td>{device.serial}</td></tr>"
if device.primary_ip is not None: if device.primary_ip is not None:
node_content += ( node_content += (
f"<tr><th>IP Address: </th><td>{device.primary_ip.address}</td></tr>" f"<tr><th>{_('IP Address')}: </th><td>{device.primary_ip.address}</td></tr>"
) )
if device.site is not None: if device.site is not None:
node_content += f"<tr><th>Site: </th><td>{device.site.name}</td></tr>" node_content += f"<tr><th>{_('Site')}: </th><td>{device.site.name}</td></tr>"
if device.location is not None: if device.location is not None:
node_content += ( node_content += (
f"<tr><th>Location: </th><td>{device.location.name}</td></tr>" f"<tr><th>{_('Location')}: </th><td>{device.location.name}</td></tr>"
) )
if device.rack is not None: if device.rack is not None:
node_content += f"<tr><th>Rack: </th><td>{device.rack.name}</td></tr>" node_content += f"<tr><th>{_('Rack')}: </th><td>{device.rack.name}</td></tr>"
if device.position is not None: if device.position is not None:
if device.face is not None: if device.face is not None:
node_content += f"<tr><th>Position: </th><td>{device.position} ({device.face})</td></tr>" node_content += f"<tr><th>{_('Position')}: </th><td>{device.position} ({device.face})</td></tr>"
else: else:
node_content += ( node_content += (
f"<tr><th>Position: </th><td>{device.position}</td></tr>" f"<tr><th>{_('Position')}: </th><td>{device.position}</td></tr>"
) )
node["id"] = device.pk node["id"] = device.pk
@@ -281,22 +283,22 @@ def create_edge(
interface: Optional[Interface] = None, interface: Optional[Interface] = None,
): ):
cable_a_name = ( cable_a_name = (
"device A name unknown" _("termination A name unknown")
if termination_a["termination_name"] is None if termination_a["termination_name"] is None
else termination_a["termination_name"] else termination_a["termination_name"]
) )
cable_a_dev_name = ( cable_a_dev_name = (
"device A name unknown" _("device A name unknown")
if termination_a["termination_device_name"] is None if termination_a["termination_device_name"] is None
else termination_a["termination_device_name"] else termination_a["termination_device_name"]
) )
cable_b_name = ( cable_b_name = (
"device A name unknown" _("termination B name unknown")
if termination_b["termination_name"] is None if termination_b["termination_name"] is None
else termination_b["termination_name"] else termination_b["termination_name"]
) )
cable_b_dev_name = ( cable_b_dev_name = (
"cable B name unknown" _("device B name unknown")
if termination_b["termination_device_name"] is None if termination_b["termination_device_name"] is None
else termination_b["termination_device_name"] else termination_b["termination_device_name"]
) )
@@ -306,29 +308,29 @@ def create_edge(
edge["from"] = termination_a["device_id"] edge["from"] = termination_a["device_id"]
edge["to"] = termination_b["device_id"] edge["to"] = termination_b["device_id"]
edge["color"] = '#2b7ce9' edge["color"] = '#2b7ce9'
title = "Cable" title = _("Cable")
if circuit is not None: if circuit is not None:
edge["dashes"] = True edge["dashes"] = True
title = f"Circuit provider: {circuit['provider_name']}<br>Termination" title = _("Circuit provider: %(provider)s<br>Termination") % {"provider": circuit['provider_name']}
elif wireless is not None: elif wireless is not None:
edge["dashes"] = LinePattern().wireless edge["dashes"] = LinePattern().wireless
title = "Wireless Connection" title = _("Wireless Connection")
elif power is not None: elif power is not None:
edge["dashes"] = LinePattern().power edge["dashes"] = LinePattern().power
title = "Power Connection" title = _("Power Connection")
elif interface is not None: elif interface is not None:
title = "Interface Connection" title = _("Interface Connection")
edge["width"] = 3 edge["width"] = 3
edge["dashes"] = LinePattern().logical edge["dashes"] = LinePattern().logical
edge["color"] = '#f1c232' edge["color"] = '#f1c232'
edge["href"] = interface.get_absolute_url() + "trace" edge["href"] = interface.get_absolute_url() + "trace"
if cable is not None and hasattr(cable, "label") and cable.label: if cable is not None and hasattr(cable, "label") and cable.label:
cable_label = "<br>Label: " + cable.label cable_label = "<br>" + _("Label: %(label)s") % {"label": cable.label}
if draw_cable_labels is True: if draw_cable_labels is True:
edge["label"] = cable.label edge["label"] = cable.label
else: else:
@@ -336,7 +338,13 @@ def create_edge(
edge[ edge[
"title" "title"
] = f"{title} between<br>{cable_a_dev_name} [{cable_a_name}]<br>{cable_b_dev_name} [{cable_b_name}] {cable_label}" ] = _("%(title)s between<br>%(device_a)s [%(termination_a)s]<br>%(device_b)s [%(termination_b)s]") % {
"title": title,
"device_a": cable_a_dev_name,
"termination_a": cable_a_name,
"device_b": cable_b_dev_name,
"termination_b": cable_b_name,
} + f" {cable_label}"
if cable is not None: if cable is not None:
edge["href"] = cable.get_absolute_url() edge["href"] = cable.get_absolute_url()
@@ -921,12 +929,19 @@ def _rack_endpoint(termination):
return { return {
"node_id": f"device-{device.pk}" if device else f"external-{termination._meta.model_name}-{termination.pk}", "node_id": f"device-{device.pk}" if device else f"external-{termination._meta.model_name}-{termination.pk}",
"device_id": getattr(device, "pk", None), "device_id": getattr(device, "pk", None),
"device_name": getattr(device, "name", None) or "External", "device_name": getattr(device, "name", None) or _("External"),
"name": getattr(termination, "name", str(termination)), "name": getattr(termination, "name", str(termination)),
"rack_id": getattr(device, "rack_id", None), "rack_id": getattr(device, "rack_id", None),
"rack_name": getattr(getattr(device, "rack", None), "name", None) or "Extern", "rack_name": getattr(getattr(device, "rack", None), "name", None) or _("External"),
"url": device.get_absolute_url() if device else None, "url": device.get_absolute_url() if device else None,
"color": getattr(getattr(device, "role", None), "color", None) or "1685fc", "color": getattr(getattr(device, "role", None), "color", None) or "1685fc",
"position": float(device.position or 1) if device else None,
"height": float(max(getattr(getattr(device, "device_type", None), "u_height", 1) or 1, 1)) if device else 1,
"face": str(device.face or "front").lower() if device else "front",
"rack_u_height": getattr(getattr(device, "rack", None), "u_height", None),
"rack_desc_units": getattr(getattr(device, "rack", None), "desc_units", False),
"rack_starting_unit": getattr(getattr(device, "rack", None), "starting_unit", 1),
"subtitle": str(device.device_type) if device else getattr(termination, "name", str(termination)),
} }
@@ -960,32 +975,49 @@ class RackElevationView(PermissionRequiredMixin, View):
device_ids = [] device_ids = []
for device in devices.filter(rack_id__in=rack_ids).order_by("rack_id", "position", "name"): for device in devices.filter(rack_id__in=rack_ids).order_by("rack_id", "position", "name"):
device_ids.append(device.pk) device_ids.append(device.pk)
height = max(getattr(device.device_type, "u_height", 1) or 1, 1) height = float(max(getattr(device.device_type, "u_height", 1) or 1, 1))
rack_height = max(device.rack.u_height or 1, 1) rack_height = max(device.rack.u_height or 1, 1)
device.elevation_bottom = f"{(float(device.position or 1) - 1) / rack_height * 100:.4f}" rack_start = float(device.rack.starting_unit or 1)
position_offset = float(device.position or rack_start) - rack_start
if device.rack.desc_units:
bottom_units = rack_height - position_offset - height
else:
bottom_units = position_offset
device.elevation_bottom = f"{max(bottom_units, 0) / rack_height * 100:.4f}"
device.elevation_height = f"{min(height / rack_height * 100, 100):.4f}" device.elevation_height = f"{min(height / rack_height * 100, 100):.4f}"
device.elevation_face = str(device.face or "front").lower() device.elevation_face = str(device.face or "front").lower()
rack_devices[device.rack_id].append(device) rack_devices[device.rack_id].append(device)
for rack in rack_list: for rack in rack_list:
rack.elevation_devices = rack_devices[rack.pk] rack.elevation_devices = rack_devices[rack.pk]
rack.elevation_unit_labels = range(rack.u_height or 0, 0, -1) rack_start = rack.starting_unit or 1
if rack.desc_units:
rack.elevation_unit_labels = range(rack_start, rack_start + (rack.u_height or 0))
else:
rack.elevation_unit_labels = range(
rack_start + (rack.u_height or 0) - 1,
rack_start - 1,
-1,
)
rack_export = [] rack_export = []
for rack in rack_list: for rack in rack_list:
rack_export.append({ rack_export.append({
"id": rack.pk, "name": rack.name, "u_height": rack.u_height, "id": rack.pk, "name": rack.name, "u_height": rack.u_height,
"starting_unit": rack.starting_unit, "desc_units": rack.desc_units,
"site": str(rack.site), "location": str(rack.location or ""), "site": str(rack.site), "location": str(rack.location or ""),
"devices": [{ "devices": [{
"name": device.name or str(device.device_type), "name": device.name or str(device.device_type),
"type": str(device.device_type), "type": str(device.device_type),
"position": float(device.position or 1), "position": float(device.position or 1),
"height": max(device.device_type.u_height or 1, 1), "height": float(max(device.device_type.u_height or 1, 1)),
"face": device.elevation_face, "face": device.elevation_face,
"color": f"#{device.role.color}" if device.role.color else "#1685fc", "color": f"#{device.role.color}" if device.role.color else "#1685fc",
} for device in rack.elevation_devices], } for device in rack.elevation_devices],
}) })
power_component_models = {"powerport", "poweroutlet", "powerfeed"}
cable_rows = [] cable_rows = []
topology_nodes = {} topology_nodes = {}
topology_edges = [] topology_edges = []
@@ -996,6 +1028,9 @@ class RackElevationView(PermissionRequiredMixin, View):
cables = Cable.objects.restrict(request.user, "view").filter(pk__in=cable_ids) cables = Cable.objects.restrict(request.user, "view").filter(pk__in=cable_ids)
for cable in cables.order_by("label", "pk"): for cable in cables.order_by("label", "pk"):
a_terms, b_terms = list(cable.a_terminations), list(cable.b_terminations) a_terms, b_terms = list(cable.a_terminations), list(cable.b_terminations)
is_power_cable = cable.type == CableTypeChoices.TYPE_POWER or any(
term._meta.model_name in power_component_models for term in a_terms + b_terms
)
for index in range(max(len(a_terms), len(b_terms), 1)): for index in range(max(len(a_terms), len(b_terms), 1)):
a = _rack_endpoint(a_terms[index]) if index < len(a_terms) else None a = _rack_endpoint(a_terms[index]) if index < len(a_terms) else None
b = _rack_endpoint(b_terms[index]) if index < len(b_terms) else None b = _rack_endpoint(b_terms[index]) if index < len(b_terms) else None
@@ -1005,22 +1040,89 @@ class RackElevationView(PermissionRequiredMixin, View):
if endpoint: if endpoint:
topology_nodes[endpoint["node_id"]] = endpoint topology_nodes[endpoint["node_id"]] = endpoint
if a and b: if a and b:
default_color = "#f59e0b" if is_power_cable else "#1685fc"
topology_edges.append({ topology_edges.append({
"from": a["node_id"], "to": b["node_id"], "from": a["node_id"], "to": b["node_id"],
"from_device": a["device_name"], "to_device": b["device_name"], "from_device": a["device_name"], "to_device": b["device_name"],
"from_port": a["name"], "to_port": b["name"], "from_port": a["name"], "to_port": b["name"],
"label": cable.label or str(cable), "label": cable.label or str(cable),
"color": f"#{cable.color}" if cable.color else "#1685fc", "color": f"#{cable.color}" if cable.color else default_color,
"url": cable.get_absolute_url(), "url": cable.get_absolute_url(),
"kind": "power" if is_power_cable else "cable",
}) })
wireless_device_ids = set(device_ids) | {
node["device_id"] for node in topology_nodes.values() if node.get("device_id")
}
wireless_links = WirelessLink.objects.restrict(request.user, "view").filter(
Q(interface_a__device_id__in=wireless_device_ids) |
Q(interface_b__device_id__in=wireless_device_ids)
).select_related(
"interface_a__device__rack", "interface_a__device__role", "interface_a__device__device_type",
"interface_b__device__rack", "interface_b__device__role", "interface_b__device__device_type",
)
for wireless_link in wireless_links:
a = _rack_endpoint(wireless_link.interface_a)
b = _rack_endpoint(wireless_link.interface_b)
topology_nodes[a["node_id"]] = a
topology_nodes[b["node_id"]] = b
topology_edges.append({
"from": a["node_id"], "to": b["node_id"],
"from_device": a["device_name"], "to_device": b["device_name"],
"from_port": a["name"], "to_port": b["name"],
"label": wireless_link.ssid or str(wireless_link),
"color": "#8b5cf6", "url": wireless_link.get_absolute_url(),
"kind": "wireless",
})
wireless_lans = WirelessLAN.objects.restrict(request.user, "view").filter(
interfaces__device_id__in=device_ids
).distinct()
for wireless_lan in wireless_lans:
wlan_node_id = f"wlan-{wireless_lan.pk}"
topology_nodes[wlan_node_id] = {
"node_id": wlan_node_id, "device_id": None,
"device_name": f"WLAN · {wireless_lan.ssid}",
"name": wireless_lan.ssid, "subtitle": _("Multi-Access WLAN"),
"rack_id": None, "rack_name": _("Wireless networks"),
"url": wireless_lan.get_absolute_url(), "color": "8b5cf6",
"position": None, "height": 1, "face": "front", "rack_u_height": None,
"kind": "wireless-lan",
}
wlan_interfaces = Interface.objects.restrict(request.user, "view").filter(
wireless_lans=wireless_lan
).select_related("device__rack", "device__role", "device__device_type")
for interface in wlan_interfaces:
endpoint = _rack_endpoint(interface)
topology_nodes[endpoint["node_id"]] = endpoint
topology_edges.append({
"from": endpoint["node_id"], "to": wlan_node_id,
"from_device": endpoint["device_name"],
"to_device": f"WLAN · {wireless_lan.ssid}",
"from_port": endpoint["name"], "to_port": wireless_lan.ssid,
"label": wireless_lan.ssid, "color": "#8b5cf6",
"url": wireless_lan.get_absolute_url(), "kind": "wireless-lan",
})
return render(request, "netbox_topology_views/rack_elevation.html", { return render(request, "netbox_topology_views/rack_elevation.html", {
"filter_form": RackElevationFilterForm(request.GET or None), "filter_form": RackElevationFilterForm(request.GET or None),
"racks": rack_list, "cables": cable_rows, "racks": rack_list, "cables": cable_rows,
"rack_topology": {"nodes": list(topology_nodes.values()), "edges": topology_edges}, "rack_topology": {"nodes": list(topology_nodes.values()), "edges": topology_edges},
"rack_export": rack_export, "rack_export": rack_export,
"faces": (("front", "Vorderseite"), ("rear", "Rückseite")), "faces": (("front", _("Front")), ("rear", _("Rear"))),
"has_selection": bool(request.GET), "has_selection": bool(request.GET),
# Labels for the inline script, which cannot use template tags
"i18n": {
"external": _("External"),
"power": _("Power"),
"connections": _("Connections"),
"noConnections": _("No connections"),
"fullScreen": _("Full screen"),
"exitFullScreen": _("Exit full screen"),
"device": _("Device"),
"front": _("Front"),
"rear": _("Rear"),
},
}) })
@@ -1317,7 +1419,7 @@ class TopologyIndividualOptionsView(PermissionRequiredMixin, View):
form = IndividualOptionsForm(request.POST, instance=instance) form = IndividualOptionsForm(request.POST, instance=instance)
if form.is_valid(): if form.is_valid():
form.save() form.save()
messages.success(request, "Options have been sucessfully saved") messages.success(request, _("Options have been successfully saved"))
else: else:
messages.error(request, form.errors) messages.error(request, form.errors)
+1 -1
View File
@@ -7,7 +7,7 @@ long_description = readme.read_text()
setup( setup(
name="netbox-topology-views", name="netbox-topology-views",
version="4.5.1", version="4.5.2",
description="A NetBox plugin to create Topology maps", description="A NetBox plugin to create Topology maps",
long_description=long_description, long_description=long_description,
long_description_content_type="text/markdown", long_description_content_type="text/markdown",
+37
View File
@@ -0,0 +1,37 @@
"""Keeps the NetBox range in README.md in sync with the PluginConfig."""
import ast
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def plugin_versions():
tree = ast.parse((ROOT / "netbox_topology_views" / "__init__.py").read_text())
values = {}
for node in ast.walk(tree):
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in ("min_version", "max_version"):
values[target.id] = node.value.value
return values["min_version"], values["max_version"]
def expected_range(min_version, max_version):
upper = re.sub(r"\.99$", ".x", max_version)
if min_version.endswith(".0") and upper == min_version[:-2] + ".x":
return f"`{upper}`"
return f"`{min_version}` – `{upper}`"
class MetadataTest(unittest.TestCase):
def test_readme_matches_plugin_config(self):
readme = (ROOT / "README.md").read_text()
expected = expected_range(*plugin_versions())
self.assertIn(f"| **NetBox** | {expected} |", readme)
self.assertIn(f"- NetBox {expected}", readme)
if __name__ == "__main__":
unittest.main()