Compare commits
27
Commits
e477aa9b49
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27673ee68f | ||
|
|
174a41e838 | ||
|
|
d7c86289b1 | ||
|
|
9735164da1 | ||
|
|
38b3ec2a27 | ||
|
|
4405a65653 | ||
|
|
ca29980aa6 | ||
|
|
55c70814c3 | ||
|
|
4ec96bf65d | ||
|
|
59ffd2a4b5 | ||
|
|
cd4357f417 | ||
|
|
c888a65180 | ||
|
|
74dfa0ec61 | ||
|
|
2c0e026cb9 | ||
|
|
9dba7e07a0 | ||
|
|
0d046f3a9d | ||
|
|
3cf26c8ded | ||
|
|
a796b92056 | ||
|
|
5514c974f1 | ||
|
|
ad8632ed24 | ||
|
|
0aa9403cb9 | ||
|
|
0cd72824d5 | ||
|
|
3ad7cc6810 | ||
|
|
cbf09c219c | ||
|
|
bce880f5d7 | ||
|
|
e3c31b6312 | ||
|
|
062413a2cd |
No files matched your search
@@ -1,249 +1,369 @@
|
|||||||
# NetBox Customer Export
|
# NetBox Customer Export
|
||||||
|
|
||||||
NetBox-Plugin (4.6.8 – 4.7.99) zum Export einer verständlichen **Kundendokumentation als PDF oder Word**
|
Export clear, customer-facing documentation as **PDF or Word** for a **site,
|
||||||
für einen **Standort, eine Lokation, einen Mandanten oder eine Mandantengruppe**.
|
location, tenant or tenant group**.
|
||||||
|
|
||||||
Der Techniker wählt vor dem Export aus, welche Inhalte das Dokument enthalten soll:
|
| | |
|
||||||
|
|
||||||
| Gruppe | Inhalte |
|
|
||||||
|---|---|
|
|---|---|
|
||||||
| Allgemein | Übersicht & Standortdaten (Adresse, Lokationsbaum, Kennzahlen), Ansprechpartner |
|
| **Plugin name** | `netbox_customer_export` |
|
||||||
| Infrastruktur | Racks nach Standort → Lokation mit Rack-Ansicht (Vorder-/Rückseite, optional mit Gerätebildern wie in NetBox) und Belegungsliste, Geräte nach **frei wählbaren Geräterollen** (Server, Switche, APs, Router …) mit **frei wählbaren Spalten**, Stromversorgung, VMs |
|
| **Package** | `netbox-customer-export` |
|
||||||
| Netzwerk | VRFs (inkl. RTs), Präfixe nach VRF, VLANs, IP-Adressen (ausführlich), WLANs/SSIDs, Leitungen, **Netzwerk-Topologie** |
|
| **NetBox** | `4.6.8` – `4.7.x` |
|
||||||
| Verträge & Lizenzen | Lizenzen aus einem Lizenz-Plugin (Standard: `netbox-lifecycle`) |
|
| **Python** | `>=3.10` |
|
||||||
|
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-Customer-Export> |
|
||||||
|
|
||||||
Alle Abfragen laufen über die NetBox-Berechtigungen (`.restrict(user, "view")`). Ein Techniker exportiert also nur, was er auch sehen darf.
|
## Screenshots
|
||||||
|
|
||||||
## Aufruf
|
Scope selection for a customer documentation export:
|
||||||
|
|
||||||
* Button **„Kundendoku“** auf Standort-, Lokations-, Mandanten- und Mandantengruppen-Seiten
|

|
||||||
* oder Menü **Plugins → Kundendokumentation**
|
|
||||||
|
|
||||||
Formate: **PDF**, **Word**, **HTML-Vorschau** (öffnet in neuem Tab) und **draw.io** (nur Topologie, editierbar).
|
Branding profiles for exported documents:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
Before exporting, the technician selects which content the document contains:
|
||||||
|
|
||||||
|
| Group | Content |
|
||||||
|
|---|---|
|
||||||
|
| General | Overview & site data (address, location tree, key figures), contacts |
|
||||||
|
| Infrastructure | Racks by site → location with rack elevation (front/rear, optionally with device images as in NetBox) occupancy list and optional **rack photos** in an appendix, devices by **selectable device roles** (servers, switches, APs, routers …) with **selectable columns**, power, **virtualization clusters** with resources, VMs, **disks & RAID** from [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) (if installed), **floor plans** from [NetBox-FloorPlan](https://git.mrblake.cc/MrBlake/NetBox-FloorPlan2.0) (if installed) |
|
||||||
|
| Network | VRFs (incl. RTs), prefixes by VRF, VLANs, IP addresses (detailed), WLANs/SSIDs, circuits, **network topology** |
|
||||||
|
| Contracts & licenses | Licenses from [NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM) (detected automatically) or another license plugin (e.g. `netbox-lifecycle`) |
|
||||||
|
|
||||||
|
**IP versions** (IPv4, IPv6 or both) control which addresses appear in the
|
||||||
|
document: management/OOB IPs, VMs, topology labels, prefixes and IP addresses.
|
||||||
|
|
||||||
|
All queries respect NetBox permissions (`.restrict(user, "view")`) — a
|
||||||
|
technician only exports what they are allowed to see.
|
||||||
|
|
||||||
|
Open it via the **Customer Docs** button on site, location, tenant and tenant
|
||||||
|
group pages, or via **Customer Export → Customer Documentation** in the main navigation. Output formats:
|
||||||
|
**PDF**, **Word** and **HTML preview** (opens in a new tab).
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
- NetBox `4.6.8` – `4.7.x`
|
||||||
|
- Python `>=3.10`
|
||||||
|
- System libraries for PDF and rack graphics in Word: Pango, Cairo
|
||||||
|
- Languages: English and German. The interface and the exported documents follow
|
||||||
|
the language set in the user's NetBox preferences.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
Die Pfade gehen von einer Standardinstallation unter `/opt/netbox` aus.
|
All paths assume a standard installation under `/opt/netbox`.
|
||||||
|
|
||||||
### 1. Systembibliotheken (für PDF und Rack-Grafiken in Word)
|
### 0. System libraries
|
||||||
|
|
||||||
|
Required for PDF output and rack graphics in Word:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install -y libpango-1.0-0 libpangoft2-1.0-0 libcairo2 git
|
sudo apt install -y libpango-1.0-0 libpangoft2-1.0-0 libcairo2 git
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Plugin per Git installieren
|
### 1. Install the package
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
source /opt/netbox/venv/bin/activate
|
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
|
||||||
pip install "netbox-customer-export[all] @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git"
|
"netbox-customer-export[all] @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git@main"
|
||||||
```
|
```
|
||||||
|
|
||||||
Die Extras regeln, was mitinstalliert wird:
|
The extras control what is installed alongside:
|
||||||
|
|
||||||
| Extra | Pakete | Formate |
|
| Extra | Packages | Formats |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `[all]` | weasyprint, python-docx, cairosvg | PDF + Word + HTML |
|
| `[all]` | weasyprint, python-docx, cairosvg | PDF + Word + HTML |
|
||||||
| `[pdf]` | weasyprint | PDF + HTML |
|
| `[pdf]` | weasyprint | PDF + HTML |
|
||||||
| `[docx]` | python-docx, cairosvg | Word + HTML |
|
| `[docx]` | python-docx, cairosvg | Word + HTML |
|
||||||
|
|
||||||
Eine bestimmte Version (Tag oder Commit) installierst du mit `@<tag>` hinter der URL, z.B.
|
For reproducible production installs, replace `main` with a release tag or a
|
||||||
`git+https://git.mrblake.cc/MrBlake/[email protected]`.
|
full commit ID.
|
||||||
|
|
||||||
### 3. In `local_requirements.txt` aufnehmen
|
### 2. Add the plugin to `local_requirements.txt`
|
||||||
|
|
||||||
NetBox' `upgrade.sh` legt das venv bei jedem NetBox-Update neu an. Nur Pakete aus `local_requirements.txt` werden danach
|
This makes `upgrade.sh` reinstall the plugin automatically on every NetBox upgrade:
|
||||||
automatisch wieder installiert. Deshalb das Plugin dort eintragen:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
echo 'netbox-customer-export[all] @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git' \
|
grep -qxF "netbox-customer-export[all] @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git@main" /opt/netbox/local_requirements.txt \
|
||||||
| sudo tee -a /opt/netbox/local_requirements.txt
|
|| echo "netbox-customer-export[all] @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git@main" | sudo tee -a /opt/netbox/local_requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
Soll eine feste Version eingespielt werden, trägst du dort ebenfalls `@<tag>` ein.
|
If the repository is private, the NetBox server needs a read-only deploy token
|
||||||
|
or an SSH key. Do not store credentials in `local_requirements.txt`.
|
||||||
|
|
||||||
### 4. In `configuration.py` aktivieren
|
### 3. Enable the plugin
|
||||||
|
|
||||||
`/opt/netbox/netbox/netbox/configuration.py`:
|
In `/opt/netbox/netbox/netbox/configuration.py`:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
PLUGINS = ["netbox_customer_export"]
|
PLUGINS = [
|
||||||
|
"netbox_customer_export",
|
||||||
|
]
|
||||||
|
|
||||||
PLUGINS_CONFIG = {
|
PLUGINS_CONFIG = {
|
||||||
"netbox_customer_export": {
|
"netbox_customer_export": {
|
||||||
"company_name": "Meine IT GmbH", # Branding-Optionen siehe unten
|
"company_name": "My IT Ltd", # branding options: see below
|
||||||
"logo_path": "/opt/netbox/branding/logo.png",
|
"logo_path": "/opt/netbox/branding/logo.png",
|
||||||
"footer_text": "Vertraulich",
|
"footer_text": "Confidential",
|
||||||
# Offline-Rack-SVG aus Netbox-Utilities (mehrere Geräte pro HE):
|
# Offline rack SVG from Netbox-Utilities (multiple devices per U):
|
||||||
# Funktion mit Signatur fn(rack, face, user) -> SVG-String
|
# function with signature fn(rack, face, user) -> SVG string
|
||||||
"rack_svg_renderer": None, # z.B. "netbox_utilities.<modul>.<funktion>"
|
"rack_svg_renderer": None, # e.g. "netbox_utilities.<module>.<function>"
|
||||||
"allow_secrets": False, # WLAN-PSK-Export erlauben
|
"allow_secrets": False, # allow exporting WLAN PSKs / license keys
|
||||||
# "license_sources": [ { "model": "app.model", "device_field": "device",
|
# "license_sources": [ { "model": "app.model", "device_field": "device",
|
||||||
# "tenant_field": "tenant", "columns": [("Lizenz", "license"), ...] } ],
|
# "tenant_field": "tenant", "columns": [("License", "license"), ...] } ],
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5. Migrationen, statische Dateien, Neustart
|
If other plugins are already configured, add `netbox_customer_export` to the
|
||||||
|
existing list and dictionary instead of replacing them.
|
||||||
|
|
||||||
|
### 4. Apply migrations, collect static files, restart
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
source /opt/netbox/venv/bin/activate
|
|
||||||
cd /opt/netbox/netbox
|
cd /opt/netbox/netbox
|
||||||
python3 manage.py migrate
|
/opt/netbox/venv/bin/python manage.py migrate netbox_customer_export
|
||||||
python3 manage.py collectstatic --no-input
|
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
|
||||||
python3 manage.py remove_stale_contenttypes --no-input
|
/opt/netbox/venv/bin/python manage.py remove_stale_contenttypes --no-input
|
||||||
python3 manage.py clearsessions
|
/opt/netbox/venv/bin/python manage.py clearsessions
|
||||||
sudo systemctl restart netbox netbox-rq
|
sudo systemctl restart netbox netbox-rq
|
||||||
```
|
```
|
||||||
|
|
||||||
`migrate` ist ab Version 0.2.0 **Pflicht**, denn es legt die Tabellen für Branding-Profile und (ab 0.4.0) Topologie-Symbole an. Die übrigen Befehle gehören zum
|
`migrate` is mandatory since version 0.2.0: it creates the tables for branding
|
||||||
üblichen NetBox-Ablauf nach jeder Plugin-Installation.
|
profiles and topology symbols.
|
||||||
|
|
||||||
## Update
|
## Update
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
source /opt/netbox/venv/bin/activate
|
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall --no-deps \
|
||||||
pip install --upgrade --force-reinstall --no-deps "netbox-customer-export @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git"
|
"netbox-customer-export @ git+https://git.mrblake.cc/MrBlake/NetBox-Customer-Export.git@main"
|
||||||
```
|
|
||||||
|
|
||||||
Danach wie bei der Installation:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
source /opt/netbox/venv/bin/activate
|
|
||||||
cd /opt/netbox/netbox
|
cd /opt/netbox/netbox
|
||||||
python3 manage.py migrate
|
/opt/netbox/venv/bin/python manage.py migrate netbox_customer_export
|
||||||
python3 manage.py collectstatic --no-input
|
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
|
||||||
python3 manage.py remove_stale_contenttypes --no-input
|
|
||||||
python3 manage.py clearsessions
|
|
||||||
sudo systemctl restart netbox netbox-rq
|
sudo systemctl restart netbox netbox-rq
|
||||||
```
|
```
|
||||||
|
|
||||||
`--force-reinstall` ist nötig, weil pip ein Git-Paket mit unveränderter Versionsnummer sonst nicht neu holt.
|
`--force-reinstall` makes pip pick up branch changes even if the package
|
||||||
`--no-deps` verhindert, dass dabei auch WeasyPrint & Co. neu installiert werden. Bei einer festen Version in
|
version has not been bumped. `--no-deps` avoids reinstalling WeasyPrint & co.
|
||||||
`local_requirements.txt` dort den Tag anpassen und denselben Befehl mit `@<neuer-tag>` ausführen.
|
|
||||||
|
|
||||||
Installierte Version prüfen:
|
When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from
|
||||||
|
`local_requirements.txt` and runs migrations and `collectstatic`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip show netbox-customer-export
|
sudo /opt/netbox/upgrade.sh
|
||||||
|
sudo systemctl restart netbox netbox-rq
|
||||||
```
|
```
|
||||||
|
|
||||||
### NetBox-Update
|
If you pinned a release tag in `local_requirements.txt`, change the tag there
|
||||||
|
before running the upgrade. Check first that the plugin supports the new NetBox
|
||||||
|
version (`min_version`/`max_version`), otherwise NetBox refuses to start.
|
||||||
|
|
||||||
Beim NetBox-Update installiert `sudo /opt/netbox/upgrade.sh` das Plugin automatisch aus `local_requirements.txt` neu.
|
Check the installed version:
|
||||||
Vorher prüfen, ob die Plugin-Version die neue NetBox-Version unterstützt (`min_version`/`max_version`, aktuell 4.6.8 – 4.7.99).
|
|
||||||
Andernfalls verweigert NetBox den Start.
|
|
||||||
|
|
||||||
## Deinstallation
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# "netbox_customer_export" aus PLUGINS in configuration.py entfernen, dann:
|
/opt/netbox/venv/bin/pip show netbox-customer-export
|
||||||
source /opt/netbox/venv/bin/activate
|
```
|
||||||
pip uninstall netbox-customer-export
|
|
||||||
|
## Uninstall
|
||||||
|
|
||||||
|
1. Remove `"netbox_customer_export"` from `PLUGINS` and `PLUGINS_CONFIG`.
|
||||||
|
2. Remove the line from `/opt/netbox/local_requirements.txt`.
|
||||||
|
3. Uninstall the package and restart NetBox:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
/opt/netbox/venv/bin/pip uninstall netbox-customer-export
|
||||||
sudo sed -i '/netbox-customer-export/d' /opt/netbox/local_requirements.txt
|
sudo sed -i '/netbox-customer-export/d' /opt/netbox/local_requirements.txt
|
||||||
sudo systemctl restart netbox netbox-rq
|
sudo systemctl restart netbox netbox-rq
|
||||||
```
|
```
|
||||||
|
|
||||||
## Konfiguration
|
## Configuration
|
||||||
|
|
||||||
### Design / Branding in NetBox (empfohlen)
|
### Branding in NetBox (recommended)
|
||||||
|
|
||||||
Unter **Plugins → Branding-Profile** legen Admins Design-Profile direkt in NetBox an:
|
Under **Customer Export → Branding Profiles**, admins create design profiles directly in NetBox:
|
||||||
|
|
||||||
* Name, Firmenname, Fußzeile und **Logo-Upload** (PNG/JPG)
|
- name, company name, footer and **logo upload** (PNG/JPG)
|
||||||
* Farben per Farbwähler: Primär, Akzent, Tabellenkopf-Schrift, Beschriftungen, Zebrastreifen
|
- colours via colour picker: primary, accent, table header text, labels, zebra stripes
|
||||||
* Schriftart und -größe
|
- font family and size
|
||||||
* **Upload einer Word-Vorlage** (.docx/.dotx), optional mit dem Namen einer Tabellenformatvorlage
|
- **Word template upload** (`.docx`/`.dotx`), optionally with the name of a table style
|
||||||
* zusätzliches CSS für PDF und HTML
|
- extra CSS for PDF and HTML
|
||||||
* **Vorschau**-Button, der ein Beispieldokument im gewählten Design öffnet
|
- **Preview** button that opens a sample document in the selected design
|
||||||
* Ein Profil lässt sich als **Standard** markieren und ist dann im Exportformular vorausgewählt.
|
- one profile can be marked as **default** and is preselected in the export form
|
||||||
|
|
||||||
Uploads landen unter `MEDIA_ROOT/customer-export/` (Standard: `/opt/netbox/netbox/media/customer-export/`) und sollten mitgesichert werden.
|
Uploads are stored under `MEDIA_ROOT/customer-export/` (default:
|
||||||
Beim Löschen eines Profils werden Logo und Vorlage mit entfernt.
|
`/opt/netbox/netbox/media/customer-export/`) and should be backed up. Deleting a
|
||||||
|
profile also removes its logo and template.
|
||||||
|
|
||||||
**Berechtigungen:** Superuser dürfen alles. Anderen Benutzern oder Gruppen weist man unter *Admin → Berechtigungen* eine
|
**Permissions:** superusers can do everything. Other users or groups need a
|
||||||
Berechtigung für den Objekttyp *Customer Export | Branding-Profil* zu. Mit *Ansehen* sieht man Liste und Vorschau, zum Pflegen
|
permission for the object type *Customer Export | Branding profile*
|
||||||
braucht es zusätzlich *Hinzufügen*, *Ändern* und *Löschen*. Techniker, die nur exportieren, benötigen keine davon.
|
(*View* for list and preview; *Add*, *Change*, *Delete* to maintain profiles).
|
||||||
|
Technicians who only export need none of these.
|
||||||
|
|
||||||
Sind in NetBox Profile angelegt, erscheinen sie zuerst in der Auswahl „Design / Firma“. Profile aus `configuration.py`
|
Profiles created in NetBox appear first in the "Design / Company" selection;
|
||||||
(siehe unten) werden zusätzlich angeboten, wenn dort `brandings` definiert ist.
|
profiles from `configuration.py` are offered additionally if `brandings` is defined.
|
||||||
|
|
||||||
### Design / Branding per `configuration.py`
|
### Branding via `configuration.py`
|
||||||
|
|
||||||
Alternativ oder ergänzend lassen sich Profile in der Konfiguration festlegen, entweder global oder als **mehrere Profile**
|
Profiles can also be defined in the configuration — globally or as **multiple
|
||||||
(z.B. pro eigener Firma oder Marke). Die globalen Werte gelten als Basis, jedes Profil überschreibt nur die Werte, die es selbst setzt.
|
profiles** (e.g. per company or brand). Global values are the base; each
|
||||||
|
profile only overrides the values it sets.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
PLUGINS_CONFIG = {
|
PLUGINS_CONFIG = {
|
||||||
"netbox_customer_export": {
|
"netbox_customer_export": {
|
||||||
"company_name": "Meine IT GmbH", # Basis für alle Profile
|
"company_name": "My IT Ltd", # base for all profiles
|
||||||
"brandings": {
|
"brandings": {
|
||||||
"standard": {"name": "Meine IT GmbH", "logo_path": "/opt/netbox/branding/logo.png"},
|
"standard": {"name": "My IT Ltd", "logo_path": "/opt/netbox/branding/logo.png"},
|
||||||
"partner": {
|
"partner": {
|
||||||
"name": "Partner AG",
|
"name": "Partner Inc",
|
||||||
"company_name": "Partner AG",
|
"company_name": "Partner Inc",
|
||||||
"logo_path": "/opt/netbox/branding/partner.png",
|
"logo_path": "/opt/netbox/branding/partner.png",
|
||||||
"primary_color": "#C00000",
|
"primary_color": "#C00000",
|
||||||
"accent_color": "#E46C0A",
|
"accent_color": "#E46C0A",
|
||||||
"font_family": "Arial",
|
"font_family": "Arial",
|
||||||
"docx_template": "/opt/netbox/branding/partner.dotx",
|
"docx_template": "/opt/netbox/branding/partner.dotx",
|
||||||
"docx_table_style": "Gitternetztabelle 4 – Akzent 1",
|
"docx_table_style": "Grid Table 4 - Accent 1",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| Schlüssel | Standard | Wirkung |
|
| Key | Default | Effect |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `name` | Profilschlüssel | Anzeigename im Formular |
|
| `name` | profile key | Display name in the form |
|
||||||
| `company_name`, `logo_path`, `footer_text` | – | Deckblatt und Fußzeile |
|
| `company_name`, `logo_path`, `footer_text` | – | Cover page and footer |
|
||||||
| `primary_color` | `1F4E79` | Überschriften, Tabellenköpfe |
|
| `primary_color` | `1F4E79` | Headings, table headers |
|
||||||
| `accent_color` | `2E75B6` | Unterüberschriften (Ebene 3/4) |
|
| `accent_color` | `2E75B6` | Sub-headings (level 3/4) |
|
||||||
| `header_text_color` | `FFFFFF` | Schrift im Tabellenkopf |
|
| `header_text_color` | `FFFFFF` | Table header text |
|
||||||
| `label_bg_color` | `DEEAF6` | Beschriftungsspalte der Detailtabellen |
|
| `label_bg_color` | `DEEAF6` | Label column of detail tables |
|
||||||
| `stripe_color` | `F3F7FB` | Zebrastreifen (PDF) |
|
| `stripe_color` | `F3F7FB` | Zebra stripes (PDF) |
|
||||||
| `font_family`, `font_size` | `Calibri`, `10` | Grundschrift |
|
| `font_family`, `font_size` | `Calibri`, `10` | Base font |
|
||||||
| `docx_template` | – | `.docx`/`.dotx`: Formatvorlagen, Kopf-/Fußzeile und Ränder werden übernommen, der Textinhalt der Vorlage wird verworfen |
|
| `docx_template` | – | `.docx`/`.dotx`: styles, header/footer and margins are used, the template's text content is discarded |
|
||||||
| `docx_table_style` | – | Name einer Tabellenformatvorlage aus der Vorlage (so, wie er in Word angezeigt wird). Ist er gesetzt, entfällt die eigene Einfärbung. |
|
| `docx_table_style` | – | Name of a table style from the template (as shown in Word). If set, the plugin's own colouring is skipped. |
|
||||||
| `extra_css` | – | zusätzliches CSS für PDF/HTML |
|
| `extra_css` | – | Extra CSS for PDF/HTML |
|
||||||
|
|
||||||
Farben werden als Hex angegeben, mit oder ohne `#`. Ungültige Werte führen beim Export zu einer klaren Fehlermeldung.
|
Colours are hex values with or without `#`; invalid values produce a clear
|
||||||
Mit einer Word-Vorlage bestimmt die Vorlage die Überschriften-Formate. Ohne Vorlage färbt das Plugin die Überschriften selbst ein.
|
error message on export. With a Word template, the template defines the heading
|
||||||
Bringt die Vorlage eine eigene Fußzeile mit, wird diese beibehalten.
|
styles and its own footer is kept.
|
||||||
|
|
||||||
### Netzwerk-Topologie
|
### Network topology
|
||||||
|
|
||||||
Der Abschnitt **Netzwerk-Topologie** zeichnet je Standort ein Diagramm mit Symbolen im Stil von Cisco Packet Tracer:
|
The **Network topology** section draws one diagram per site with icons in the
|
||||||
|
style of Cisco Packet Tracer:
|
||||||
|
|
||||||
* Verbindungen stammen aus den **Kabelpfaden** in NetBox. Pfade über Patchpanels werden bis zum Endgerät verfolgt.
|
- Links come from NetBox **cable paths**; paths through patch panels are traced to the end device.
|
||||||
* Die Anordnung von oben nach unten ergibt sich aus der Verkabelung: Provider → Firewall/Router → Core → Access → Endgeräte.
|
- The top-to-bottom layout follows the cabling: provider → firewall/router → core → access → end devices, with ordering optimised for as few crossings as possible.
|
||||||
Mehrfach-Uplinks werden als „2ד markiert.
|
- Lines are routed **orthogonally** on bus bars, coloured per upstream device. Port names sit at the target device; multiple uplinks are drawn thicker and marked "2×".
|
||||||
* Provider-Leitungen erscheinen als Wolke, Geräte anderer Standorte gestrichelt (abschaltbar).
|
- **Scope**: *entire network* (one page per site), *location overview* and/or *per rack* (one page per rack). In the rack view, directly connected devices outside the rack appear faded and dashed, with their rack.
|
||||||
* Beschriftung wählbar: Management-IP, Modell, Ports an den Verbindungen.
|
- The **location overview** draws one diagram per site with the **locations as nodes** (server room, halls, sub-distributions …). Lines are the physical cables between locations, labelled with count and cable type (e.g. `2× SMF, 4× CAT6a`), so you can follow the cabling from the server room to the last sub-distribution. Locations containing firewalls, routers or core switches are placed at the top; each node shows its parent location and the number of racks and devices. Devices without a location (e.g. radio bridges on the roof) are grouped in a node for their site ("without location").
|
||||||
* Mit dem Format **draw.io** wird die Topologie als editierbare `.drawio`-Datei exportiert, eine Seite je Standort.
|
- The **cross-site location overview** puts all locations of all sites in scope into **one diagram**; each node shows its site (and parent location), so you can see how buildings and their locations are connected to each other.
|
||||||
|
- Each topology gets its **own landscape page** (PDF and Word) and is scaled as large as possible.
|
||||||
|
- Provider circuits appear as a cloud, devices of other sites dashed (can be disabled).
|
||||||
|
- **Wireless links** (NetBox *Wireless links*, e.g. point-to-point radio bridges) appear as blue dotted lines labelled "Wireless", in the network view as well as in the location overviews.
|
||||||
|
- Selectable labels: management IP, model, ports on links.
|
||||||
|
- Device names longer than 15 characters are wrapped, preferably at `-`, `_`, `.` or spaces.
|
||||||
|
|
||||||
**Symbole** (Menü **Plugins → Topologie-Symbole**, oder Button „Topologie-Symbol“ auf Gerätetyp- und Geräterollen-Seiten):
|
**Symbols** (menu **Customer Export → Topology Symbols**, or the "Topology symbol"
|
||||||
|
button on device type and device role pages):
|
||||||
|
|
||||||
1. Zuordnung je **Gerätetyp**: eingebautes Symbol wählen oder **eigenes Icon hochladen** (PNG/JPG, idealerweise transparent)
|
1. per **device type**: choose a built-in symbol or **upload a custom icon** (PNG/JPG, ideally transparent)
|
||||||
2. Zuordnung je **Geräterolle**
|
2. per **device role**
|
||||||
3. sonst **automatisch** anhand von Rolle, Modell und Hersteller (z.B. „Switch“, „Sophos“, „Access Point“, „Core“)
|
3. otherwise **automatic**, first by role, then by model and manufacturer
|
||||||
|
|
||||||
Patchpanels, Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet. Über „In Topologie ausblenden“ lassen sich
|
Built-in symbols: internet/provider, modem/NTU, firewall, router, layer-3
|
||||||
weitere Gerätetypen oder Rollen ausblenden. Eigene Icons liegen unter `MEDIA_ROOT/customer-export/symbols/`.
|
switch, switch, radio link, patch panel, WLAN controller, PoE injector, access point, server,
|
||||||
Berechtigungen: Objekttyp *Customer Export | Topologie-Symbol*, analog zu den Branding-Profilen.
|
storage/SAN, NAS, tape library, UPS/ATS, PBX, IP phone, PC/client, printer,
|
||||||
|
camera and "other".
|
||||||
|
|
||||||
### Rack-Ansichten
|
Patch panels, power strips, PDUs, cable management and rooms are hidden
|
||||||
|
automatically; further device types or roles can be hidden via "Hide in
|
||||||
|
topology". Custom icons are stored under `MEDIA_ROOT/customer-export/symbols/`.
|
||||||
|
Permissions: object type *Customer Export | Topology symbol*, analogous to
|
||||||
|
branding profiles.
|
||||||
|
|
||||||
Ohne Konfiguration nutzt das Plugin NetBox' eigenen `dcim.svg.RackElevationSVG`. Er läuft im selben Prozess, also ohne HTTP-Aufruf der API.
|
### Licenses (NetBox-SLM)
|
||||||
Soll stattdessen der Offline-Renderer aus [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) verwendet werden,
|
|
||||||
trägt man unter `rack_svg_renderer` den Pfad zu dessen Render-Funktion ein. Falls die Signatur abweicht, braucht es einen kleinen Adapter.
|
|
||||||
|
|
||||||
## Architektur
|
If [NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM) is installed, the
|
||||||
|
**Licenses** section reads its software licenses automatically — no
|
||||||
|
configuration required. A license belongs to the export if
|
||||||
|
|
||||||
|
- its **installation** is on a device, VM or cluster in the selected site/location/tenant, or
|
||||||
|
- it is assigned to the exported **tenant**, or
|
||||||
|
- it has no tenant but is assigned to a **tenant group** the tenant belongs to (including parent groups), or that lies within the exported tenant group.
|
||||||
|
|
||||||
|
Tables are grouped by manufacturer and show license, product/version, type,
|
||||||
|
quantity, term (incl. renewal), status (*active*, *expires in N days* from 90
|
||||||
|
days before expiry, *expired*, *perpetual*), support, installation and tenant.
|
||||||
|
The **license key** only appears with the "Export secrets" option (requires
|
||||||
|
`allow_secrets: True`). Additionally configured `license_sources` are still output.
|
||||||
|
|
||||||
|
### Disks & RAID (Netbox-Utilities)
|
||||||
|
|
||||||
|
If [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) with disk management is installed, the
|
||||||
|
**Disks & RAID** section (off by default) lists for each device in scope: occupied slots, raw capacity, hot spares and
|
||||||
|
failed disks, the RAID groups (level, count, usable capacity, fault tolerance) and a table of all installed disks with
|
||||||
|
slot, status, type, model, size, serial number, firmware, RAID group, optionally the install date, warranty and warnings (failed, warranty
|
||||||
|
expired/expiring soon, too old – thresholds from the Utilities configuration). Removed disks (history) are not shown.
|
||||||
|
Without the plugin the section stays empty.
|
||||||
|
|
||||||
|
### Floor plans (NetBox-FloorPlan)
|
||||||
|
|
||||||
|
If [NetBox-FloorPlan](https://git.mrblake.cc/MrBlake/NetBox-FloorPlan2.0) (`netbox_floorplanner`) is installed, the
|
||||||
|
**Floor plans** section (off by default) shows every floor plan in scope (site, location, or – for tenants – plans of the
|
||||||
|
tenant or containing its racks/devices) as a full-width drawing with room size, the background image (JPEG/PNG), and a
|
||||||
|
table of the placed racks and devices. The plugin is optional and never imported directly; without it the section stays empty.
|
||||||
|
For Word the drawing is converted with cairosvg, otherwise a simplified Pillow rendering is used.
|
||||||
|
|
||||||
|
### Rack photos
|
||||||
|
|
||||||
|
Images attached to racks in NetBox (*Attach an image*) show up as thumbnails in the
|
||||||
|
**Rack photos** card of the export form, grouped by rack. Selected photos are
|
||||||
|
placed in an appendix at the end of the document. Below each rack elevation a link
|
||||||
|
points to that rack's photos, and each appendix entry links back to the rack. Photos
|
||||||
|
are rotated according to EXIF and scaled down to 1600 px. In Word the links are internal
|
||||||
|
hyperlinks to bookmarks.
|
||||||
|
|
||||||
|
### Virtualization clusters
|
||||||
|
|
||||||
|
The **Virtualization clusters** section (off by default) lists every cluster with hosts
|
||||||
|
or VMs in scope: an overview table, then per cluster type, group, status, tenant and the
|
||||||
|
summed vCPU, RAM and disk of its VMs, plus a host table with VMs, vCPU and RAM per host.
|
||||||
|
Only VMs inside the export scope are counted, so a tenant export does not reveal other
|
||||||
|
tenants' VMs on a shared cluster.
|
||||||
|
|
||||||
|
### CPU & RAM (Netbox-Utilities)
|
||||||
|
|
||||||
|
If [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) with CPU & RAM is installed:
|
||||||
|
|
||||||
|
- Device tables offer the columns **CPU** (model, count, cores/threads) and **RAM** (total, modules, type and speed).
|
||||||
|
- The **Virtualization clusters** section adds the physical cores/threads and RAM of the hosts and shows the overcommitment: vCPU per physical core (e.g. `2,6 : 1`) and assigned VM RAM as a percentage of host RAM, per cluster and per host.
|
||||||
|
|
||||||
|
RAM is shown in binary units like in Netbox-Utilities (1 GB = 1024 MB), so VM and host values are comparable. Without the plugin the columns stay empty and the cluster section shows VM totals only.
|
||||||
|
|
||||||
|
### Rack elevations
|
||||||
|
|
||||||
|
By default the plugin uses NetBox's own `dcim.svg.RackElevationSVG` in-process
|
||||||
|
(no HTTP call to the API). To use the offline renderer from
|
||||||
|
[Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) instead,
|
||||||
|
set `rack_svg_renderer` to the path of its render function. A small adapter is
|
||||||
|
needed if the signature differs.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
```
|
```
|
||||||
scope.py welche Objekte gehören zum Scope (Standort/Lokation/Mandant/-gruppe)
|
scope.py which objects belong to the scope (site/location/tenant/group)
|
||||||
sections.py Registry der Abschnitte (@section-Dekorator) → neutrale Blöcke
|
sections.py registry of sections (@section decorator) → neutral blocks
|
||||||
blocks.py Dokumentmodell (Überschrift, Tabelle, Key/Value, Bilder, Umbruch)
|
blocks.py document model (heading, table, key/value, images, page break)
|
||||||
renderers/ html (→ WeasyPrint-PDF), docx (python-docx + cairosvg)
|
renderers/ html (→ WeasyPrint PDF), docx (python-docx + cairosvg)
|
||||||
```
|
```
|
||||||
|
|
||||||
Einen neuen Abschnitt hinzufügen: in `sections.py` eine Funktion mit `@section("key", "Label", "Gruppe")` schreiben, die eine Liste von Blöcken zurückgibt. Er erscheint automatisch im Formular und in beiden Formaten.
|
To add a section, write a function in `sections.py` decorated with
|
||||||
|
`@section("key", "Label", "Group")` that returns a list of blocks. It appears
|
||||||
|
automatically in the form and in both output formats.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Apache License 2.0.
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 74 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
@@ -1,11 +1,12 @@
|
|||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
from netbox.plugins import PluginConfig
|
from netbox.plugins import PluginConfig
|
||||||
|
|
||||||
|
|
||||||
class CustomerExportConfig(PluginConfig):
|
class CustomerExportConfig(PluginConfig):
|
||||||
name = "netbox_customer_export"
|
name = "netbox_customer_export"
|
||||||
verbose_name = "Kunden-Export"
|
verbose_name = _("Customer Export")
|
||||||
description = "Kundendokumentation als PDF oder Word exportieren"
|
description = _("Export customer documentation as PDF or Word")
|
||||||
version = "0.4.0"
|
version = "0.19.1"
|
||||||
author = "Claude"
|
author = "Claude"
|
||||||
base_url = "customer-export"
|
base_url = "customer-export"
|
||||||
min_version = "4.6.8"
|
min_version = "4.6.8"
|
||||||
|
|||||||
@@ -3,13 +3,14 @@ import base64
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
from django.utils.text import slugify
|
from django.utils.text import slugify
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
EMPTY = "—"
|
EMPTY = "—"
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Block:
|
class Block:
|
||||||
kind: str # heading | paragraph | table | kv | images | pagebreak
|
kind: str # heading | paragraph | ref | table | kv | images | pagebreak | landscape
|
||||||
level: int = 0
|
level: int = 0
|
||||||
text: str = ""
|
text: str = ""
|
||||||
headers: list = field(default_factory=list)
|
headers: list = field(default_factory=list)
|
||||||
@@ -28,7 +29,11 @@ class Document:
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def toc(self):
|
def toc(self):
|
||||||
return [b for b in self.blocks if b.kind == "heading" and b.level <= 2]
|
out = []
|
||||||
|
for b in self.blocks:
|
||||||
|
headings = b.rows if b.kind == "landscape" else [b]
|
||||||
|
out += [h for h in headings if h.kind == "heading" and h.level <= 2]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
_anchor_counter = {"n": 0}
|
_anchor_counter = {"n": 0}
|
||||||
@@ -43,27 +48,40 @@ def P(text):
|
|||||||
return Block("paragraph", text=str(text))
|
return Block("paragraph", text=str(text))
|
||||||
|
|
||||||
|
|
||||||
|
def REF(text, target, prefix=""):
|
||||||
|
"""Interner Verweis auf eine Überschrift (target = deren anchor); prefix bleibt unverlinkt."""
|
||||||
|
return Block("ref", text=str(text), anchor=target, rows=[prefix])
|
||||||
|
|
||||||
|
|
||||||
def T(headers, rows):
|
def T(headers, rows):
|
||||||
return Block("table", headers=list(headers), rows=[[fmt(c) for c in r] for r in rows])
|
return Block("table", headers=[str(h) for h in headers], rows=[[fmt(c) for c in r] for r in rows])
|
||||||
|
|
||||||
|
|
||||||
def KV(pairs, skip_empty=True):
|
def KV(pairs, skip_empty=True):
|
||||||
rows = [[k, fmt(v)] for k, v in pairs if not (skip_empty and v in (None, "", [], EMPTY))]
|
rows = [[str(k), fmt(v)] for k, v in pairs if not (skip_empty and v in (None, "", [], EMPTY))]
|
||||||
return Block("kv", rows=rows)
|
return Block("kv", rows=rows)
|
||||||
|
|
||||||
|
|
||||||
def IMAGES(images, wide=False):
|
def IMAGES(images, wide=False, photos=False):
|
||||||
"""images: Liste von (svg_string oder None, caption, png_bytes_oder_None)."""
|
"""images: Liste von (svg_string oder None, caption, png_bytes_oder_None). Statt PNG geht auch JPEG."""
|
||||||
out = []
|
out = []
|
||||||
for svg, caption, png in images:
|
for svg, caption, png in images:
|
||||||
if svg:
|
if svg:
|
||||||
data_uri = "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii")
|
data_uri = "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii")
|
||||||
elif png:
|
elif png:
|
||||||
data_uri = "data:image/png;base64," + base64.b64encode(png).decode("ascii")
|
mime = "image/jpeg" if png[:2] == bytes((0xFF, 0xD8)) else "image/png"
|
||||||
|
data_uri = f"data:{mime};base64," + base64.b64encode(png).decode("ascii")
|
||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
out.append({"svg": svg, "png": png, "caption": caption, "data_uri": data_uri})
|
out.append({"svg": svg, "png": png, "caption": caption, "data_uri": data_uri})
|
||||||
return Block("images", images=out, level=1 if wide else 0) # level=1: volle Seitenbreite
|
# level=1: volle Seitenbreite, level=2: Fotos (zwei je Zeile)
|
||||||
|
return Block("images", images=out, level=2 if photos else 1 if wide else 0)
|
||||||
|
|
||||||
|
|
||||||
|
def LANDSCAPE(headings, png):
|
||||||
|
"""Eigene Seite im Querformat: Überschriften + Bild so groß wie möglich (z.B. Topologie)."""
|
||||||
|
data_uri = "data:image/png;base64," + base64.b64encode(png).decode("ascii")
|
||||||
|
return Block("landscape", rows=list(headings), images=[{"svg": None, "png": png, "caption": "", "data_uri": data_uri}])
|
||||||
|
|
||||||
|
|
||||||
def PAGEBREAK():
|
def PAGEBREAK():
|
||||||
@@ -74,7 +92,7 @@ def fmt(value):
|
|||||||
if value is None or value == "":
|
if value is None or value == "":
|
||||||
return EMPTY
|
return EMPTY
|
||||||
if isinstance(value, bool):
|
if isinstance(value, bool):
|
||||||
return "Ja" if value else "Nein"
|
return _("Yes") if value else _("No")
|
||||||
if isinstance(value, (list, tuple, set)) or hasattr(value, "all"):
|
if isinstance(value, (list, tuple, set)) or hasattr(value, "all"):
|
||||||
items = value.all() if hasattr(value, "all") else value
|
items = value.all() if hasattr(value, "all") else value
|
||||||
return ", ".join(str(i) for i in items) or EMPTY
|
return ", ".join(str(i) for i in items) or EMPTY
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ from netbox.plugins import get_plugin_config
|
|||||||
PLUGIN = "netbox_customer_export"
|
PLUGIN = "netbox_customer_export"
|
||||||
|
|
||||||
DEFAULT_BRANDING = {
|
DEFAULT_BRANDING = {
|
||||||
"name": "Standard",
|
"name": "Default",
|
||||||
"company_name": "",
|
"company_name": "",
|
||||||
"logo_path": None,
|
"logo_path": None,
|
||||||
"footer_text": "Vertraulich – nur für den internen Gebrauch des Kunden",
|
"footer_text": "Confidential – for the customer's internal use only",
|
||||||
"primary_color": "1F4E79", # Überschriften, Tabellenköpfe
|
"primary_color": "1F4E79", # Überschriften, Tabellenköpfe
|
||||||
"accent_color": "2E75B6", # Unterüberschriften
|
"accent_color": "2E75B6", # Unterüberschriften
|
||||||
"header_text_color": "FFFFFF", # Schrift im Tabellenkopf
|
"header_text_color": "FFFFFF", # Schrift im Tabellenkopf
|
||||||
@@ -31,7 +31,7 @@ def _normalize(profile):
|
|||||||
for key in COLOR_KEYS:
|
for key in COLOR_KEYS:
|
||||||
value = str(profile[key]).lstrip("#")
|
value = str(profile[key]).lstrip("#")
|
||||||
if not _HEX.match(value):
|
if not _HEX.match(value):
|
||||||
raise ValueError(f"netbox_customer_export: {key}={profile[key]!r} ist keine Hex-Farbe (z.B. '1F4E79')")
|
raise ValueError(f"netbox_customer_export: {key}={profile[key]!r} is not a hex colour (e.g. '1F4E79')")
|
||||||
profile[key] = value.upper()
|
profile[key] = value.upper()
|
||||||
return profile
|
return profile
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ from django.contrib.auth.mixins import PermissionRequiredMixin
|
|||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.shortcuts import get_object_or_404, redirect, render
|
from django.shortcuts import get_object_or_404, redirect, render
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from django.utils.formats import date_format
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
from django.views import View
|
from django.views import View
|
||||||
|
|
||||||
from .blocks import KV, P, T, Document, H
|
from .blocks import KV, P, T, Document, H
|
||||||
@@ -40,7 +42,7 @@ class BrandingEditView(PermissionRequiredMixin, View):
|
|||||||
form = BrandingProfileForm(request.POST, request.FILES, instance=obj)
|
form = BrandingProfileForm(request.POST, request.FILES, instance=obj)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
obj = form.save()
|
obj = form.save()
|
||||||
messages.success(request, f"Branding-Profil „{obj}“ gespeichert.")
|
messages.success(request, _("Branding profile “%(name)s” saved.") % {"name": obj})
|
||||||
return redirect(f"plugins:{APP}:branding_list")
|
return redirect(f"plugins:{APP}:branding_list")
|
||||||
return render(request, self.template_name, {"object": obj, "form": form})
|
return render(request, self.template_name, {"object": obj, "form": form})
|
||||||
|
|
||||||
@@ -58,7 +60,7 @@ class BrandingDeleteView(PermissionRequiredMixin, View):
|
|||||||
if f:
|
if f:
|
||||||
f.delete(save=False)
|
f.delete(save=False)
|
||||||
obj.delete()
|
obj.delete()
|
||||||
messages.success(request, f"Branding-Profil „{name}“ gelöscht.")
|
messages.success(request, _("Branding profile “%(name)s” deleted.") % {"name": name})
|
||||||
return redirect(f"plugins:{APP}:branding_list")
|
return redirect(f"plugins:{APP}:branding_list")
|
||||||
|
|
||||||
|
|
||||||
@@ -70,24 +72,24 @@ class BrandingPreviewView(PermissionRequiredMixin, View):
|
|||||||
def get(self, request, pk):
|
def get(self, request, pk):
|
||||||
obj = get_object_or_404(BrandingProfile, pk=pk)
|
obj = get_object_or_404(BrandingProfile, pk=pk)
|
||||||
blocks = [
|
blocks = [
|
||||||
H(1, "Übersicht"),
|
H(1, _("Overview")),
|
||||||
KV([("Standort", "Musterstandort"), ("Status", "Aktiv"), ("Anschrift", "Musterstraße 1\n12345 Musterstadt")]),
|
KV([(_("Site"), _("Sample site")), (_("Status"), _("Active")), (_("Address"), _("1 Sample Street\nSample City"))]),
|
||||||
H(2, "Geräte"),
|
H(2, _("Devices")),
|
||||||
T(
|
T(
|
||||||
["Name", "Hersteller / Modell", "Rack / HE", "Management-IP"],
|
[_("Name"), _("Manufacturer / model"), _("Rack / U"), _("Management IP")],
|
||||||
[
|
[
|
||||||
["SW-CORE-01", "HPE Aruba 6100", "Rack A / HE 20", "10.0.0.2/24"],
|
["SW-CORE-01", "HPE Aruba 6100", _("Rack A / U %(u)s") % {"u": 20}, "10.0.0.2/24"],
|
||||||
["SW-ACC-01", "HPE Aruba 6000", "Rack A / HE 18", "10.0.0.3/24"],
|
["SW-ACC-01", "HPE Aruba 6000", _("Rack A / U %(u)s") % {"u": 18}, "10.0.0.3/24"],
|
||||||
["FW-01", "Sophos XGS 2100", "Rack A / HE 16", "10.0.0.1/24"],
|
["FW-01", "Sophos XGS 2100", _("Rack A / U %(u)s") % {"u": 16}, "10.0.0.1/24"],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
P("So sehen Überschriften, Tabellen und Fließtext mit diesem Profil aus."),
|
P(_("This is how headings, tables and body text look with this profile.")),
|
||||||
]
|
]
|
||||||
doc = Document(
|
doc = Document(
|
||||||
title="Netzwerkdokumentation Vorschau",
|
title=_("Network documentation preview"),
|
||||||
subtitle="Beispielkunde",
|
subtitle=_("Sample customer"),
|
||||||
blocks=blocks,
|
blocks=blocks,
|
||||||
meta={"author": request.user.username, "date": timezone.localtime().strftime("%d.%m.%Y")},
|
meta={"author": request.user.username, "date": date_format(timezone.localdate(), "SHORT_DATE_FORMAT")},
|
||||||
branding=_normalize(obj.as_branding()),
|
branding=_normalize(obj.as_branding()),
|
||||||
)
|
)
|
||||||
return HttpResponse(render_html(doc), content_type="text/html; charset=utf-8")
|
return HttpResponse(render_html(doc), content_type="text/html; charset=utf-8")
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""Datenträger und RAID-Gruppen aus dem Plugin Netbox-Utilities (netbox_utilities.Disk)."""
|
||||||
|
from django.apps import apps
|
||||||
|
from django.utils.formats import date_format
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
from .blocks import EMPTY, H, KV, T
|
||||||
|
|
||||||
|
ACTIVE_STATUSES = ("active", "spare", "failed", "planned") # ohne „ausgebaut/ersetzt“
|
||||||
|
|
||||||
|
|
||||||
|
def is_installed():
|
||||||
|
if not apps.is_installed("netbox_utilities"):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
apps.get_model("netbox_utilities", "Disk")
|
||||||
|
except LookupError: # ältere Version ohne Datenträger
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _helpers():
|
||||||
|
from netbox_utilities import disks
|
||||||
|
|
||||||
|
return disks
|
||||||
|
|
||||||
|
|
||||||
|
def _date(value):
|
||||||
|
return date_format(value, "SHORT_DATE_FORMAT") if value else None
|
||||||
|
|
||||||
|
|
||||||
|
def _slot(disk):
|
||||||
|
bay = disk.bay.name if disk.bay_id and disk.device.netbox_utilities_disk_bays.count() > 1 else ""
|
||||||
|
return f"{bay} {disk.slot}".strip()
|
||||||
|
|
||||||
|
|
||||||
|
def disk_blocks(scope, opts):
|
||||||
|
"""Je Gerät: Kennzahlen, RAID-Gruppen und Datenträger. Leer, wenn keine Datenträger im Scope."""
|
||||||
|
Disk = apps.get_model("netbox_utilities", "Disk")
|
||||||
|
RAIDGroup = apps.get_model("netbox_utilities", "RAIDGroup")
|
||||||
|
DiskBayLayout = apps.get_model("netbox_utilities", "DiskBayLayout")
|
||||||
|
helpers = _helpers()
|
||||||
|
fmt = helpers.format_capacity
|
||||||
|
warn_cfg = helpers.warning_settings()
|
||||||
|
|
||||||
|
disks = list(
|
||||||
|
scope.restrict(Disk.objects.filter(device__in=scope.devices(), status__in=ACTIVE_STATUSES))
|
||||||
|
.select_related("device", "bay", "raid_group")
|
||||||
|
.order_by("device__name", "bay__weight", "bay__name", "slot")
|
||||||
|
)
|
||||||
|
if not disks:
|
||||||
|
return []
|
||||||
|
|
||||||
|
by_device = {}
|
||||||
|
for disk in disks:
|
||||||
|
by_device.setdefault(disk.device, []).append(disk)
|
||||||
|
|
||||||
|
show_installed = bool(opts.get("disk_install_date"))
|
||||||
|
headers = [_("Slot"), _("Status"), _("Disk"), _("Size"), _("Serial number"), "RAID"]
|
||||||
|
headers += [_("Installed")] * show_installed + [_("Warranty until"), _("Notes")]
|
||||||
|
blocks = []
|
||||||
|
for device, items in by_device.items():
|
||||||
|
slots = sum(b.slot_count for b in DiskBayLayout.objects.filter(device=device))
|
||||||
|
summary = helpers.disk_summary(items, slots)
|
||||||
|
blocks.append(H(2, device.name or str(device)))
|
||||||
|
blocks.append(KV([
|
||||||
|
(_("Slots used"), f"{summary['used']} / {slots}" if slots else summary["used"]),
|
||||||
|
(_("Raw capacity"), fmt(summary["raw_capacity_gb"])),
|
||||||
|
(_("Hot spares"), summary["spares"]),
|
||||||
|
(_("Failed"), summary["failed"]),
|
||||||
|
]))
|
||||||
|
|
||||||
|
groups = list(RAIDGroup.objects.filter(device=device).order_by("name"))
|
||||||
|
if groups:
|
||||||
|
rows = []
|
||||||
|
for group in groups:
|
||||||
|
members = [d for d in items if d.raid_group_id == group.pk and d.status in ("active", "failed")]
|
||||||
|
usable, tolerated, _err = helpers.raid_usable_capacity(group.level, [d.capacity_gb for d in members], group.spans)
|
||||||
|
rows.append([
|
||||||
|
group.name,
|
||||||
|
group.get_level_display(),
|
||||||
|
len(members),
|
||||||
|
fmt(usable) if usable else EMPTY,
|
||||||
|
tolerated if tolerated is not None else EMPTY,
|
||||||
|
group.description,
|
||||||
|
])
|
||||||
|
blocks.append(T([_("RAID group"), _("Level"), _("Disks"), _("Usable"), _("Fault tolerance"), _("Description")], rows))
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for d in items:
|
||||||
|
hints = "\n".join(text for _lvl, text in helpers.disk_warnings(d, **warn_cfg))
|
||||||
|
row = [
|
||||||
|
_slot(d),
|
||||||
|
d.get_status_display(),
|
||||||
|
"\n".join(x for x in (
|
||||||
|
" ".join(x for x in (d.manufacturer, d.model) if x),
|
||||||
|
" / ".join(x for x in (d.get_disk_type_display(), d.get_interface_display()) if x),
|
||||||
|
) if x),
|
||||||
|
fmt(d.capacity_gb) if d.capacity_gb else None,
|
||||||
|
"\n".join(x for x in (d.serial, f"FW {d.firmware}" if d.firmware else "") if x),
|
||||||
|
d.raid_group.name if d.raid_group_id else None,
|
||||||
|
]
|
||||||
|
if show_installed:
|
||||||
|
row.append(_date(getattr(d, "install_date", None)))
|
||||||
|
rows.append(row + [_date(d.warranty_end), hints])
|
||||||
|
blocks.append(T(headers, rows))
|
||||||
|
return blocks
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
"""Raumpläne aus dem Plugin NetBox-FloorPlan (netbox_floorplanner.FloorPlan / FloorPlanItem).
|
||||||
|
|
||||||
|
Optional: Ohne das Plugin liefert ``is_installed()`` False und der Abschnitt bleibt leer.
|
||||||
|
Es wird nichts aus ``netbox_floorplanner`` importiert, Modelle kommen nur über die App-Registry.
|
||||||
|
Das SVG ist eigenständig (feste Farben, eingebettetes Hintergrundbild), damit es in PDF und Word
|
||||||
|
(cairosvg) gleich aussieht; für Word ohne cairosvg gibt es ein vereinfachtes Pillow-PNG.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import math
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.utils.html import escape
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
from .blocks import H, IMAGES, KV, P, T
|
||||||
|
|
||||||
|
APP = "netbox_floorplanner"
|
||||||
|
|
||||||
|
TYPE_COLORS = {
|
||||||
|
"area": "#22c55e", "wall": "#475569", "door": "#b45309", "window": "#0ea5e9", "column": "#64748b",
|
||||||
|
"rack": "#3b82f6", "device": "#8b5cf6", "cooling": "#06b6d4", "power": "#f59e0b", "label": "#334155",
|
||||||
|
}
|
||||||
|
FILLED = ("rack", "device", "cooling", "power")
|
||||||
|
FLOOR, WALL, MUTED = "#ffffff", "#334155", "#6c757d"
|
||||||
|
|
||||||
|
|
||||||
|
def is_installed():
|
||||||
|
if not apps.is_installed(APP):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
apps.get_model(APP, "FloorPlan")
|
||||||
|
apps.get_model(APP, "FloorPlanItem")
|
||||||
|
except LookupError:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _models():
|
||||||
|
return apps.get_model(APP, "FloorPlan"), apps.get_model(APP, "FloorPlanItem")
|
||||||
|
|
||||||
|
|
||||||
|
def floorplans(scope):
|
||||||
|
"""Raumpläne im Scope. Mandanten: Pläne des Mandanten oder mit dessen Racks/Geräten."""
|
||||||
|
FloorPlan, _ = _models()
|
||||||
|
if scope.kind == "site":
|
||||||
|
q = Q(site=scope.obj)
|
||||||
|
elif scope.kind == "location":
|
||||||
|
q = Q(location__in=scope.locations)
|
||||||
|
else:
|
||||||
|
q = Q(tenant__in=scope.tenants) | Q(items__rack__tenant__in=scope.tenants) | Q(items__device__tenant__in=scope.tenants)
|
||||||
|
qs = FloorPlan.objects.filter(q).distinct().select_related("site", "location", "tenant")
|
||||||
|
return scope.restrict(qs).order_by("site__name", "location__name", "name")
|
||||||
|
|
||||||
|
|
||||||
|
def meters(cm):
|
||||||
|
return f"{cm / 100:.2f}".rstrip("0").rstrip(".").replace(".", ",")
|
||||||
|
|
||||||
|
|
||||||
|
def _items(plan):
|
||||||
|
_, Item = _models()
|
||||||
|
return list(Item.objects.filter(floorplan=plan).select_related("rack", "device").order_by("z_index", "pk"))
|
||||||
|
|
||||||
|
|
||||||
|
def _text(item):
|
||||||
|
return item.label or (item.rack.name if item.rack_id else item.device.name if item.device_id else "")
|
||||||
|
|
||||||
|
|
||||||
|
def _shade(hex_color, f=0.7):
|
||||||
|
try:
|
||||||
|
n = int(hex_color.lstrip("#"), 16)
|
||||||
|
except ValueError:
|
||||||
|
return hex_color
|
||||||
|
return "#{:02x}{:02x}{:02x}".format(*(round(((n >> s) & 255) * f) for s in (16, 8, 0)))
|
||||||
|
|
||||||
|
|
||||||
|
def _color(item):
|
||||||
|
c = item.color or TYPE_COLORS.get(item.item_type, "#868e96")
|
||||||
|
return c if len(c) == 7 and c.startswith("#") else "#868e96"
|
||||||
|
|
||||||
|
|
||||||
|
# --- SVG ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _item_svg(item):
|
||||||
|
x, y, w, h, t = item.x, item.y, item.width, item.height, item.item_type
|
||||||
|
cx, cy = x + w / 2, y + h / 2
|
||||||
|
color = _color(item)
|
||||||
|
sw = 'stroke-width="3"'
|
||||||
|
parts = []
|
||||||
|
if t == "area":
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="4" fill="{color}" fill-opacity="0.12" stroke="{color}" {sw} stroke-dasharray="12 6"/>')
|
||||||
|
elif t in ("wall", "door"):
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}"/>')
|
||||||
|
if t == "door":
|
||||||
|
parts.append(f'<path d="M {x + w} {y} A {w} {w} 0 0 0 {x} {y - w} L {x} {y}" fill="{color}" fill-opacity="0.08" stroke="{color}" stroke-width="2" stroke-dasharray="6 4"/>')
|
||||||
|
elif t == "window":
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{FLOOR}" stroke="{color}" {sw}/>')
|
||||||
|
elif t == "column":
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}" fill-opacity="0.35" stroke="{color}" {sw}/>'
|
||||||
|
f'<path d="M {x} {y} L {x + w} {y + h} M {x + w} {y} L {x} {y + h}" stroke="{color}" stroke-width="2"/>')
|
||||||
|
elif t in FILLED:
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="2" fill="{color}" fill-opacity="0.85" stroke="{_shade(color)}" {sw}/>')
|
||||||
|
if t == "rack":
|
||||||
|
fh = min(h * 0.12, 10)
|
||||||
|
parts.append(f'<rect x="{x}" y="{y + h - fh}" width="{w}" height="{fh}" fill="{_shade(color)}"/>')
|
||||||
|
text = _text(item)
|
||||||
|
if text:
|
||||||
|
fs = max(8, h * 0.6) if t == "label" else max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60))
|
||||||
|
fill = "#ffffff" if t in FILLED else color if t == "label" else _shade(color)
|
||||||
|
anchor, tx, ty = ("start", x + fs * 0.5, y + fs * 1.2) if t == "area" else ("middle", cx, cy)
|
||||||
|
flip = f' transform="rotate(180 {tx} {ty})"' if 90 < item.rotation % 360 <= 270 else ""
|
||||||
|
parts.append(f'<text x="{tx}" y="{ty}" dy="0.35em" font-size="{fs:.1f}" font-weight="bold" text-anchor="{anchor}" fill="{fill}"{flip}>{escape(text)}</text>')
|
||||||
|
transform = f' transform="rotate({item.rotation} {cx} {cy})"' if item.rotation else ""
|
||||||
|
return f'<g{transform}>{"".join(parts)}</g>'
|
||||||
|
|
||||||
|
|
||||||
|
def _background(plan):
|
||||||
|
"""Hintergrundbild als (Bytes, MIME) oder None."""
|
||||||
|
if not plan.background_image:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
with plan.background_image.open("rb") as f:
|
||||||
|
data = f.read()
|
||||||
|
except Exception: # noqa: BLE001 – Datei fehlt o.Ä.: Plan ohne Hintergrund
|
||||||
|
return None
|
||||||
|
mime = "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png" if data[:4] == b"\x89PNG" else "image/webp" if data[8:12] == b"WEBP" else "image/gif"
|
||||||
|
return data, mime
|
||||||
|
|
||||||
|
|
||||||
|
def render_svg(plan, items):
|
||||||
|
width, depth = plan.width, plan.depth
|
||||||
|
fs = max(10, min(max(width, depth) * 0.025, 200))
|
||||||
|
m = fs * 2
|
||||||
|
bg = ""
|
||||||
|
if (b := _background(plan)) and b[1] in ("image/jpeg", "image/png"):
|
||||||
|
uri = f"data:{b[1]};base64," + base64.b64encode(b[0]).decode("ascii")
|
||||||
|
bg = f'<image href="{uri}" xlink:href="{uri}" x="0" y="0" width="{width}" height="{depth}" preserveAspectRatio="none" opacity="{plan.background_opacity / 100}"/>'
|
||||||
|
vw, vh = width + 2 * m, depth + 2 * m
|
||||||
|
px = 1600 / vw # feste Pixelgröße für Renderer ohne viewBox-Skalierung
|
||||||
|
return (
|
||||||
|
f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
|
||||||
|
f'width="{vw * px:.0f}" height="{vh * px:.0f}" viewBox="{-m} {-m} {vw} {vh}" font-family="DejaVu Sans, Arial, sans-serif">'
|
||||||
|
f'<rect x="{-m}" y="{-m}" width="{vw}" height="{vh}" fill="#ffffff"/>'
|
||||||
|
f'<rect x="0" y="0" width="{width}" height="{depth}" fill="{FLOOR}"/>{bg}'
|
||||||
|
f'{"".join(_item_svg(i) for i in items)}'
|
||||||
|
f'<rect x="0" y="0" width="{width}" height="{depth}" fill="none" stroke="{WALL}" stroke-width="{max(4, fs * 0.15):.1f}"/>'
|
||||||
|
f'<text x="{width / 2}" y="{-fs * 0.6}" font-size="{fs:.1f}" text-anchor="middle" fill="{MUTED}">{meters(width)} m</text>'
|
||||||
|
f'<text transform="translate({-fs * 0.6} {depth / 2}) rotate(-90)" font-size="{fs:.1f}" text-anchor="middle" fill="{MUTED}">{meters(depth)} m</text>'
|
||||||
|
f"</svg>"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --- PNG (Pillow, für Word ohne cairosvg) ---------------------------------------
|
||||||
|
|
||||||
|
def _rgb(hex_color):
|
||||||
|
n = int(hex_color.lstrip("#"), 16)
|
||||||
|
return (n >> 16) & 255, (n >> 8) & 255, n & 255
|
||||||
|
|
||||||
|
|
||||||
|
def _mix(rgb, alpha, base=(255, 255, 255)):
|
||||||
|
return tuple(round(c * alpha + b * (1 - alpha)) for c, b in zip(rgb, base))
|
||||||
|
|
||||||
|
|
||||||
|
def render_png(plan, items):
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from .rack_png import _font
|
||||||
|
|
||||||
|
width, depth = plan.width, plan.depth
|
||||||
|
fs = max(10, min(max(width, depth) * 0.025, 200))
|
||||||
|
m = fs * 2
|
||||||
|
s = 1600 / (width + 2 * m)
|
||||||
|
img = Image.new("RGB", (round((width + 2 * m) * s), round((depth + 2 * m) * s)), "white")
|
||||||
|
if (b := _background(plan)):
|
||||||
|
try:
|
||||||
|
bgi = Image.open(BytesIO(b[0])).convert("RGB").resize((max(1, round(width * s)), max(1, round(depth * s))))
|
||||||
|
img.paste(Image.blend(Image.new("RGB", bgi.size, "white"), bgi, plan.background_opacity / 100), (round(m * s), round(m * s)))
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
def pt(px_, py_):
|
||||||
|
return (px_ + m) * s, (py_ + m) * s
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
x, y, w, h, t = item.x, item.y, item.width, item.height, item.item_type
|
||||||
|
cx, cy = x + w / 2, y + h / 2
|
||||||
|
a = math.radians(item.rotation or 0)
|
||||||
|
|
||||||
|
def rot(px_, py_):
|
||||||
|
dx, dy = px_ - cx, py_ - cy
|
||||||
|
return pt(cx + dx * math.cos(a) - dy * math.sin(a), cy + dx * math.sin(a) + dy * math.cos(a))
|
||||||
|
|
||||||
|
poly = [rot(x, y), rot(x + w, y), rot(x + w, y + h), rot(x, y + h)]
|
||||||
|
c = _rgb(_color(item))
|
||||||
|
if t == "area":
|
||||||
|
d.polygon(poly, fill=_mix(c, 0.12), outline=c, width=2)
|
||||||
|
elif t in ("wall", "door"):
|
||||||
|
d.polygon(poly, fill=c)
|
||||||
|
elif t == "window":
|
||||||
|
d.polygon(poly, fill=(255, 255, 255), outline=c, width=2)
|
||||||
|
elif t == "column":
|
||||||
|
d.polygon(poly, fill=_mix(c, 0.35), outline=c, width=2)
|
||||||
|
d.line([poly[0], poly[2]], fill=c, width=1)
|
||||||
|
d.line([poly[1], poly[3]], fill=c, width=1)
|
||||||
|
elif t in FILLED:
|
||||||
|
d.polygon(poly, fill=_mix(c, 0.85), outline=_rgb(_shade(_color(item))), width=2)
|
||||||
|
text = _text(item)
|
||||||
|
if text:
|
||||||
|
size = max(8, h * 0.6) if t == "label" else max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60))
|
||||||
|
# bei 90°/270° steht der Text quer – dann an der Höhe statt der Breite ausrichten
|
||||||
|
vertical = 45 < (item.rotation or 0) % 180 < 135
|
||||||
|
if vertical and t != "label":
|
||||||
|
size = max(6, min(w * 0.3, (h * 1.6) / max(len(text), 3), 60))
|
||||||
|
fill = (255, 255, 255) if t in FILLED else c if t == "label" else _rgb(_shade(_color(item)))
|
||||||
|
font = _font(max(8, round(size * s)))
|
||||||
|
if t == "area":
|
||||||
|
d.text(rot(x + size * 0.5, y + size * 1.2), text, fill=fill, font=font, anchor="lm")
|
||||||
|
else:
|
||||||
|
d.text(pt(cx, cy), text, fill=fill, font=font, anchor="mm")
|
||||||
|
d.rectangle([pt(0, 0), pt(width, depth)], outline=_rgb(WALL), width=3)
|
||||||
|
font = _font(max(10, round(fs * s)))
|
||||||
|
d.text(pt(width / 2, -fs * 0.6), f"{meters(width)} m", fill=_rgb(MUTED), font=font, anchor="ms")
|
||||||
|
label = Image.new("RGBA", (round(fs * s * 8), round(fs * s * 1.6)), (255, 255, 255, 0))
|
||||||
|
ImageDraw.Draw(label).text((label.width / 2, label.height / 2), f"{meters(depth)} m", fill=_rgb(MUTED), font=font, anchor="mm")
|
||||||
|
label = label.rotate(90, expand=True)
|
||||||
|
lx, ly = pt(-fs * 0.6, depth / 2)
|
||||||
|
img.paste(label, (round(lx - label.width * 0.7), round(ly - label.height / 2)), label)
|
||||||
|
out = BytesIO()
|
||||||
|
img.save(out, "PNG", optimize=True)
|
||||||
|
return out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Abschnitt ----------------------------------------------------------------
|
||||||
|
|
||||||
|
def floorplan_blocks(scope, opts):
|
||||||
|
blocks = []
|
||||||
|
for plan in floorplans(scope):
|
||||||
|
items = _items(plan)
|
||||||
|
where = " / ".join(str(x) for x in (plan.site, plan.location) if x)
|
||||||
|
blocks.append(H(2, f"{plan.name} ({where})" if where else plan.name))
|
||||||
|
blocks.append(
|
||||||
|
KV(
|
||||||
|
[
|
||||||
|
(_("Site"), plan.site),
|
||||||
|
(_("Location"), plan.location),
|
||||||
|
(_("Tenant"), plan.tenant),
|
||||||
|
(_("Room size"), f"{meters(plan.width)} × {meters(plan.depth)} m"),
|
||||||
|
(_("Description"), plan.description),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
svg, png, error = None, None, None
|
||||||
|
try:
|
||||||
|
svg = render_svg(plan, items)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
error = f"{type(e).__name__}: {e}"
|
||||||
|
if opts.get("format") == "docx" or not svg:
|
||||||
|
try:
|
||||||
|
png = render_png(plan, items)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
error = f"{error or ''} / PNG: {type(e).__name__}: {e}".strip(" /")
|
||||||
|
if svg or png:
|
||||||
|
blocks.append(IMAGES([(svg, "", png)], wide=True))
|
||||||
|
else:
|
||||||
|
blocks.append(P(_("Floor plan could not be generated: %(error)s") % {"error": error}))
|
||||||
|
placed = [i for i in items if i.rack_id or i.device_id]
|
||||||
|
if placed and opts.get("floorplan_objects", True):
|
||||||
|
rows = []
|
||||||
|
for i in sorted(placed, key=lambda i: _text(i).lower()):
|
||||||
|
obj = i.rack or i.device
|
||||||
|
kind = _("Rack") if i.rack_id else _("Device")
|
||||||
|
rows.append([obj.name or str(obj), kind, i.label if i.label and i.label != obj.name else None])
|
||||||
|
blocks.append(T([_("Name"), _("Type"), _("Label in plan")], rows))
|
||||||
|
if plan.comments:
|
||||||
|
blocks.append(P(plan.comments))
|
||||||
|
return blocks
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
from django import forms
|
from django import forms
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
from dcim.models import DeviceRole, DeviceType, Location, Site
|
from dcim.models import DeviceRole, DeviceType, Location, Site
|
||||||
from netbox.plugins import get_plugin_config
|
from netbox.plugins import get_plugin_config
|
||||||
from tenancy.models import Tenant, TenantGroup
|
from tenancy.models import Tenant, TenantGroup
|
||||||
@@ -9,76 +10,99 @@ from .models import BrandingProfile, TopologySymbol
|
|||||||
from .sections import DEFAULT_DEVICE_COLUMNS, DEVICE_COLUMNS, SECTIONS
|
from .sections import DEFAULT_DEVICE_COLUMNS, DEVICE_COLUMNS, SECTIONS
|
||||||
from .symbols import KIND_CHOICES
|
from .symbols import KIND_CHOICES
|
||||||
|
|
||||||
FORMAT_CHOICES = (("pdf", "PDF"), ("docx", "Word"), ("html", "HTML-Vorschau"), ("drawio", "draw.io"))
|
FORMAT_CHOICES = (("pdf", "PDF"), ("docx", "Word"), ("html", _("HTML preview")))
|
||||||
|
|
||||||
|
|
||||||
class ScopeSelectForm(forms.Form):
|
class ScopeSelectForm(forms.Form):
|
||||||
site = DynamicModelChoiceField(queryset=Site.objects.all(), required=False, label="Standort")
|
site = DynamicModelChoiceField(queryset=Site.objects.all(), required=False, label=_("Site"))
|
||||||
location = DynamicModelChoiceField(queryset=Location.objects.all(), required=False, label="Lokation")
|
location = DynamicModelChoiceField(queryset=Location.objects.all(), required=False, label=_("Location"))
|
||||||
tenant = DynamicModelChoiceField(queryset=Tenant.objects.all(), required=False, label="Mandant")
|
tenant = DynamicModelChoiceField(queryset=Tenant.objects.all(), required=False, label=_("Tenant"))
|
||||||
tenantgroup = DynamicModelChoiceField(queryset=TenantGroup.objects.all(), required=False, label="Mandantengruppe")
|
tenantgroup = DynamicModelChoiceField(queryset=TenantGroup.objects.all(), required=False, label=_("Tenant group"))
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
data = super().clean()
|
data = super().clean()
|
||||||
chosen = [(k, v) for k, v in data.items() if v]
|
chosen = [(k, v) for k, v in data.items() if v]
|
||||||
if len(chosen) != 1:
|
if len(chosen) != 1:
|
||||||
raise forms.ValidationError("Bitte genau einen Scope auswählen.")
|
raise forms.ValidationError(_("Select exactly one scope."))
|
||||||
data["kind"], data["obj"] = chosen[0]
|
data["kind"], data["obj"] = chosen[0]
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
class ExportForm(forms.Form):
|
class ExportForm(forms.Form):
|
||||||
format = forms.ChoiceField(choices=FORMAT_CHOICES, initial="pdf", label="Format")
|
format = forms.ChoiceField(choices=FORMAT_CHOICES, initial="pdf", label=_("Format"))
|
||||||
title = forms.CharField(max_length=200, label="Titel")
|
title = forms.CharField(max_length=200, label=_("Title"))
|
||||||
subtitle = forms.CharField(max_length=200, required=False, label="Untertitel")
|
subtitle = forms.CharField(max_length=200, required=False, label=_("Subtitle"))
|
||||||
author = forms.CharField(max_length=100, required=False, label="Erstellt von")
|
author = forms.CharField(max_length=100, required=False, label=_("Created by"))
|
||||||
branding = forms.ChoiceField(choices=(), label="Design / Firma")
|
branding = forms.ChoiceField(choices=(), label=_("Design / company"))
|
||||||
|
|
||||||
sections = forms.MultipleChoiceField(
|
sections = forms.MultipleChoiceField(
|
||||||
choices=[(s.key, s.label) for s in SECTIONS.values()],
|
choices=[(s.key, s.label) for s in SECTIONS.values()],
|
||||||
initial=[s.key for s in SECTIONS.values() if s.default],
|
initial=[s.key for s in SECTIONS.values() if s.default],
|
||||||
widget=forms.CheckboxSelectMultiple,
|
widget=forms.CheckboxSelectMultiple,
|
||||||
label="Inhalte",
|
label=_("Contents"),
|
||||||
)
|
)
|
||||||
|
|
||||||
roles = forms.ModelMultipleChoiceField(
|
roles = forms.ModelMultipleChoiceField(
|
||||||
queryset=DeviceRole.objects.none(), required=False, widget=forms.CheckboxSelectMultiple, label="Geräterollen"
|
queryset=DeviceRole.objects.none(), required=False, widget=forms.CheckboxSelectMultiple, label=_("Device roles")
|
||||||
)
|
)
|
||||||
device_columns = forms.MultipleChoiceField(
|
device_columns = forms.MultipleChoiceField(
|
||||||
choices=[(k, v[0]) for k, v in DEVICE_COLUMNS.items()],
|
choices=[(k, v[0]) for k, v in DEVICE_COLUMNS.items()],
|
||||||
initial=DEFAULT_DEVICE_COLUMNS,
|
initial=DEFAULT_DEVICE_COLUMNS,
|
||||||
required=False,
|
required=False,
|
||||||
widget=forms.CheckboxSelectMultiple,
|
widget=forms.CheckboxSelectMultiple,
|
||||||
label="Gerätespalten",
|
label=_("Device columns"),
|
||||||
)
|
)
|
||||||
group_by_site = forms.BooleanField(required=False, initial=True, label="Geräte nach Standort gruppieren")
|
group_by_site = forms.BooleanField(required=False, initial=True, label=_("Group devices by site"))
|
||||||
|
|
||||||
rack_svg = forms.BooleanField(required=False, initial=True, label="Rack-Ansichten (SVG) einbetten")
|
disk_install_date = forms.BooleanField(required=False, initial=False, label=_("Show disk installation date"))
|
||||||
rack_images = forms.BooleanField(required=False, initial=False, label="Gerätebilder anzeigen (wie in NetBox)")
|
|
||||||
|
rack_svg = forms.BooleanField(required=False, initial=True, label=_("Embed rack elevations (SVG)"))
|
||||||
|
rack_images = forms.BooleanField(required=False, initial=False, label=_("Show device images (as in NetBox)"))
|
||||||
rack_faces = forms.MultipleChoiceField(
|
rack_faces = forms.MultipleChoiceField(
|
||||||
choices=(("front", "Vorderseite"), ("rear", "Rückseite")),
|
choices=(("front", _("Front")), ("rear", _("Rear"))),
|
||||||
initial=["front"],
|
initial=["front"],
|
||||||
required=False,
|
required=False,
|
||||||
widget=forms.CheckboxSelectMultiple,
|
widget=forms.CheckboxSelectMultiple,
|
||||||
label="Rack-Seiten",
|
label=_("Rack faces"),
|
||||||
)
|
)
|
||||||
rack_devices = forms.BooleanField(required=False, initial=True, label="Geräteliste je Rack")
|
rack_devices = forms.BooleanField(required=False, initial=True, label=_("Device list per rack"))
|
||||||
rack_pagebreak = forms.BooleanField(required=False, initial=True, label="Seitenumbruch nach jedem Rack")
|
rack_pagebreak = forms.BooleanField(required=False, initial=True, label=_("Page break after each rack"))
|
||||||
|
rack_photos = forms.MultipleChoiceField(choices=(), required=False, widget=forms.CheckboxSelectMultiple, label=_("Rack photos"))
|
||||||
|
|
||||||
topo_details = forms.MultipleChoiceField(
|
topo_details = forms.MultipleChoiceField(
|
||||||
choices=(("model", "Modell"), ("primary_ip", "Management-IP"), ("ports", "Ports an Verbindungen")),
|
choices=(("model", _("Model")), ("primary_ip", _("Management IP")), ("ports", _("Ports on links"))),
|
||||||
initial=["primary_ip"],
|
initial=["primary_ip"],
|
||||||
required=False,
|
required=False,
|
||||||
widget=forms.CheckboxSelectMultiple,
|
widget=forms.CheckboxSelectMultiple,
|
||||||
label="Beschriftung",
|
label=_("Labels"),
|
||||||
|
)
|
||||||
|
topo_scope = forms.MultipleChoiceField(
|
||||||
|
choices=(
|
||||||
|
("site", _("Whole network (per site)")),
|
||||||
|
("locations", _("Location overview (connections between locations)")),
|
||||||
|
("locations_all", _("Cross-site location overview (all locations in one diagram)")),
|
||||||
|
("rack", _("Per rack")),
|
||||||
|
),
|
||||||
|
initial=["site"],
|
||||||
|
required=False,
|
||||||
|
widget=forms.CheckboxSelectMultiple,
|
||||||
|
label=_("Scope"),
|
||||||
)
|
)
|
||||||
topo_external = forms.BooleanField(
|
topo_external = forms.BooleanField(
|
||||||
required=False, initial=True, label="Provider-Leitungen & Geräte außerhalb anzeigen"
|
required=False, initial=True, label=_("Show provider circuits and devices outside the scope")
|
||||||
)
|
)
|
||||||
topo_isolated = forms.BooleanField(required=False, initial=False, label="Unverkabelte Geräte anzeigen")
|
topo_isolated = forms.BooleanField(required=False, initial=False, label=_("Show uncabled devices"))
|
||||||
|
|
||||||
include_empty = forms.BooleanField(required=False, label="Leere Abschnitte trotzdem aufführen")
|
ip_versions = forms.MultipleChoiceField(
|
||||||
include_secrets = forms.BooleanField(required=False, label="Geheimnisse (z.B. WLAN-PSK) mit exportieren")
|
choices=(("4", "IPv4"), ("6", "IPv6")),
|
||||||
|
initial=["4", "6"],
|
||||||
|
required=False,
|
||||||
|
widget=forms.CheckboxSelectMultiple,
|
||||||
|
label=_("IP versions"),
|
||||||
|
)
|
||||||
|
|
||||||
|
include_empty = forms.BooleanField(required=False, label=_("List empty sections anyway"))
|
||||||
|
include_secrets = forms.BooleanField(required=False, label=_("Include secrets (e.g. Wi-Fi PSK)"))
|
||||||
|
|
||||||
def __init__(self, *args, scope=None, **kwargs):
|
def __init__(self, *args, scope=None, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
@@ -91,12 +115,18 @@ class ExportForm(forms.Form):
|
|||||||
elif isinstance(field.widget, forms.TextInput):
|
elif isinstance(field.widget, forms.TextInput):
|
||||||
field.widget.attrs["class"] = "form-control"
|
field.widget.attrs["class"] = "form-control"
|
||||||
self.fields["branding"].choices = [(k, b["name"]) for k, b in get_brandings().items()]
|
self.fields["branding"].choices = [(k, b["name"]) for k, b in get_brandings().items()]
|
||||||
|
self.photo_groups = []
|
||||||
|
if scope is not None:
|
||||||
|
from .rack_photos import grouped
|
||||||
|
|
||||||
|
self.photo_groups = grouped(scope)
|
||||||
|
self.fields["rack_photos"].choices = [(str(a.pk), a.name) for _r, atts in self.photo_groups for a in atts]
|
||||||
if scope is not None:
|
if scope is not None:
|
||||||
role_ids = scope.devices().values("role")
|
role_ids = scope.devices().values("role")
|
||||||
roles = DeviceRole.objects.filter(pk__in=role_ids).order_by("name")
|
roles = DeviceRole.objects.filter(pk__in=role_ids).order_by("name")
|
||||||
self.fields["roles"].queryset = roles
|
self.fields["roles"].queryset = roles
|
||||||
self.fields["roles"].initial = [r.pk for r in roles]
|
self.fields["roles"].initial = [r.pk for r in roles]
|
||||||
self.fields["title"].initial = f"Netzwerkdokumentation {scope.obj}"
|
self.fields["title"].initial = _("Network documentation %(name)s") % {"name": scope.obj}
|
||||||
self.fields["subtitle"].initial = f"{scope.label}: {scope.obj}"
|
self.fields["subtitle"].initial = f"{scope.label}: {scope.obj}"
|
||||||
if not get_plugin_config("netbox_customer_export", "allow_secrets"):
|
if not get_plugin_config("netbox_customer_export", "allow_secrets"):
|
||||||
del self.fields["include_secrets"]
|
del self.fields["include_secrets"]
|
||||||
@@ -127,10 +157,10 @@ class BrandingProfileForm(forms.ModelForm):
|
|||||||
"extra_css": forms.Textarea(attrs={"rows": 4, "class": "form-control font-monospace"}),
|
"extra_css": forms.Textarea(attrs={"rows": 4, "class": "form-control font-monospace"}),
|
||||||
}
|
}
|
||||||
help_texts = {
|
help_texts = {
|
||||||
"is_default": "Wird im Exportformular vorausgewählt.",
|
"is_default": _("Preselected in the export form."),
|
||||||
"logo": "PNG oder JPG, erscheint auf dem Deckblatt.",
|
"logo": _("PNG or JPG, shown on the cover page."),
|
||||||
"docx_template": ".docx oder .dotx: Formatvorlagen, Kopf-/Fußzeile und Ränder werden übernommen.",
|
"docx_template": _(".docx or .dotx: styles, header/footer and margins are applied."),
|
||||||
"docx_table_style": "Name wie in Word angezeigt, z.B. Gitternetztabelle 4 – Akzent 1. Leer = eigene Einfärbung.",
|
"docx_table_style": _("Name as shown in Word, e.g. Grid Table 4 – Accent 1. Empty = own colouring."),
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
@@ -144,17 +174,17 @@ class BrandingProfileForm(forms.ModelForm):
|
|||||||
|
|
||||||
|
|
||||||
class TopologySymbolForm(forms.ModelForm):
|
class TopologySymbolForm(forms.ModelForm):
|
||||||
device_type = DynamicModelChoiceField(queryset=DeviceType.objects.all(), required=False, label="Gerätetyp")
|
device_type = DynamicModelChoiceField(queryset=DeviceType.objects.all(), required=False, label=_("Device type"))
|
||||||
role = DynamicModelChoiceField(queryset=DeviceRole.objects.all(), required=False, label="Geräterolle")
|
role = DynamicModelChoiceField(queryset=DeviceRole.objects.all(), required=False, label=_("Device role"))
|
||||||
kind = forms.ChoiceField(
|
kind = forms.ChoiceField(
|
||||||
choices=[("", "Automatisch")] + KIND_CHOICES, required=False, widget=forms.RadioSelect, label="Symbol"
|
choices=[("", _("Automatic"))] + KIND_CHOICES, required=False, widget=forms.RadioSelect, label=_("Symbol")
|
||||||
)
|
)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = TopologySymbol
|
model = TopologySymbol
|
||||||
fields = ("device_type", "role", "kind", "icon")
|
fields = ("device_type", "role", "kind", "icon")
|
||||||
help_texts = {
|
help_texts = {
|
||||||
"icon": "PNG, JPG oder GIF, am besten quadratisch mit transparentem Hintergrund. Ersetzt das gewählte Symbol.",
|
"icon": _("PNG, JPG or GIF, ideally square with a transparent background. Replaces the selected symbol."),
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""CPU & RAM aus dem Plugin Netbox-Utilities (netbox_utilities.DeviceHardware)."""
|
||||||
|
from django.apps import apps
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
|
||||||
|
def is_installed():
|
||||||
|
if not apps.is_installed("netbox_utilities"):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
apps.get_model("netbox_utilities", "DeviceHardware")
|
||||||
|
except LookupError: # ältere Version ohne CPU & RAM
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def hardware(device):
|
||||||
|
"""DeviceHardware des Geräts oder None (nicht installiert / nicht gepflegt)."""
|
||||||
|
if not is_installed():
|
||||||
|
return None
|
||||||
|
return getattr(device, "netbox_utilities_hardware", None) # RelatedObjectDoesNotExist ist ein AttributeError
|
||||||
|
|
||||||
|
|
||||||
|
def cores_threads(hw):
|
||||||
|
"""(Kerne, Threads) gesamt oder (None, None)."""
|
||||||
|
if not hw or not hw.cpu_id:
|
||||||
|
return None, None
|
||||||
|
return hw.total_cores, hw.total_threads
|
||||||
|
|
||||||
|
|
||||||
|
def format_memory(gigabytes):
|
||||||
|
from netbox_utilities import hardware as helpers
|
||||||
|
|
||||||
|
return helpers.format_memory(gigabytes)
|
||||||
|
|
||||||
|
|
||||||
|
def cpu_text(device):
|
||||||
|
"""„2 × Intel Xeon Gold 6130“ + Zeile „32 Kerne / 64 Threads“."""
|
||||||
|
hw = hardware(device)
|
||||||
|
if not hw or not hw.cpu_id:
|
||||||
|
return None
|
||||||
|
cores, threads = cores_threads(hw)
|
||||||
|
return f"{hw.cpu_display}\n" + _("%(cores)s cores / %(threads)s threads") % {"cores": cores, "threads": threads}
|
||||||
|
|
||||||
|
|
||||||
|
def ram_text(device):
|
||||||
|
"""„384 GB“ + Zeile „12 × 32 GB · DDR4-2666“."""
|
||||||
|
hw = hardware(device)
|
||||||
|
if not hw or not hw.memory_gb:
|
||||||
|
return None
|
||||||
|
detail = hw.memory_detail
|
||||||
|
return f"{format_memory(hw.memory_gb)}\n{detail}" if detail else format_memory(hw.memory_gb)
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""Lizenzen aus dem Plugin NetBox-SLM (netbox_slm.SoftwareLicense)."""
|
||||||
|
from datetime import date
|
||||||
|
from itertools import groupby
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.utils.formats import date_format
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
from django.utils.translation import ngettext
|
||||||
|
|
||||||
|
from .blocks import EMPTY, H, T
|
||||||
|
|
||||||
|
SOON_DAYS = 90 # „läuft bald ab“, wenn das Ablaufdatum näher liegt
|
||||||
|
|
||||||
|
|
||||||
|
def is_installed():
|
||||||
|
return apps.is_installed("netbox_slm")
|
||||||
|
|
||||||
|
|
||||||
|
def _tenant_groups(scope):
|
||||||
|
"""Mandantengruppen, deren mandantenlose Lizenzen zum Scope gehören."""
|
||||||
|
from tenancy.models import TenantGroup
|
||||||
|
|
||||||
|
if scope.kind == "tenantgroup":
|
||||||
|
return scope.obj.get_descendants(include_self=True)
|
||||||
|
if scope.kind == "tenant" and scope.obj.group_id:
|
||||||
|
# Lizenzen der eigenen Gruppe und übergeordneter Gruppen gelten auch für den Mandanten
|
||||||
|
return scope.obj.group.get_ancestors(include_self=True)
|
||||||
|
return TenantGroup.objects.none()
|
||||||
|
|
||||||
|
|
||||||
|
def licenses_for_scope(scope):
|
||||||
|
"""SoftwareLicense-Queryset für den Scope: über Installationen (Gerät/VM/Cluster) und Mandant(engruppe)."""
|
||||||
|
from virtualization.models import Cluster
|
||||||
|
|
||||||
|
SoftwareLicense = apps.get_model("netbox_slm", "SoftwareLicense")
|
||||||
|
devices = scope.devices()
|
||||||
|
vms = scope.virtual_machines()
|
||||||
|
clusters = Cluster.objects.filter(Q(virtual_machines__in=vms) | Q(devices__in=devices)).distinct()
|
||||||
|
|
||||||
|
q = (
|
||||||
|
Q(installation__device__in=devices)
|
||||||
|
| Q(installation__virtualmachine__in=vms)
|
||||||
|
| Q(installation__cluster__in=clusters)
|
||||||
|
)
|
||||||
|
if scope.tenants is not None:
|
||||||
|
q |= Q(tenant__in=scope.tenants) | Q(tenant__isnull=True, tenant_group__in=_tenant_groups(scope))
|
||||||
|
return (
|
||||||
|
scope.restrict(SoftwareLicense.objects.filter(q).distinct())
|
||||||
|
.select_related(
|
||||||
|
"software_product__manufacturer", "version", "tenant", "tenant_group",
|
||||||
|
"installation__device", "installation__virtualmachine", "installation__cluster",
|
||||||
|
)
|
||||||
|
.order_by("software_product__name", "name")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validity(lic, today):
|
||||||
|
"""(Laufzeit-Text, Status-Text)."""
|
||||||
|
if lic.lifetime:
|
||||||
|
return _("unlimited"), _("active")
|
||||||
|
start = date_format(lic.start_date, "SHORT_DATE_FORMAT") if lic.start_date else ""
|
||||||
|
end = date_format(lic.expiration_date, "SHORT_DATE_FORMAT") if lic.expiration_date else ""
|
||||||
|
if start and end:
|
||||||
|
period = f"{start} – {end}"
|
||||||
|
elif end:
|
||||||
|
period = _("until %(date)s") % {"date": end}
|
||||||
|
elif start:
|
||||||
|
period = _("from %(date)s") % {"date": start}
|
||||||
|
else:
|
||||||
|
period = EMPTY
|
||||||
|
if lic.renewal_interval and lic.renewal_interval_unit:
|
||||||
|
n = lic.renewal_interval
|
||||||
|
every = {
|
||||||
|
"days": ngettext("daily", "every %(n)d days", n),
|
||||||
|
"months": ngettext("monthly", "every %(n)d months", n),
|
||||||
|
"years": ngettext("yearly", "every %(n)d years", n),
|
||||||
|
}.get(lic.renewal_interval_unit, f"{n} {lic.renewal_interval_unit}")
|
||||||
|
period += " " + _("(renewal %(interval)s)") % {"interval": every % {"n": n}}
|
||||||
|
if not lic.expiration_date:
|
||||||
|
return period, _("active")
|
||||||
|
days = (lic.expiration_date - today).days
|
||||||
|
if days < 0:
|
||||||
|
return period, _("expired")
|
||||||
|
if days <= SOON_DAYS:
|
||||||
|
return period, ngettext("expires in %(days)d day", "expires in %(days)d days", days) % {"days": days}
|
||||||
|
return period, _("active")
|
||||||
|
|
||||||
|
|
||||||
|
def _support(value):
|
||||||
|
return {True: _("Yes"), False: _("No")}.get(value, EMPTY)
|
||||||
|
|
||||||
|
|
||||||
|
def _installed_on(lic):
|
||||||
|
inst = lic.installation
|
||||||
|
if not inst:
|
||||||
|
return None
|
||||||
|
target = inst.device or inst.virtualmachine or inst.cluster
|
||||||
|
kind = _("Device") if inst.device_id else (_("VM") if inst.virtualmachine_id else _("Cluster"))
|
||||||
|
return f"{target} ({kind})" if target else None
|
||||||
|
|
||||||
|
|
||||||
|
def slm_blocks(scope, opts):
|
||||||
|
"""Tabellen je Hersteller; leer, wenn keine Lizenz zum Scope passt."""
|
||||||
|
qs = list(licenses_for_scope(scope))
|
||||||
|
if not qs:
|
||||||
|
return []
|
||||||
|
today = date.today()
|
||||||
|
show_key = bool(opts.get("include_secrets"))
|
||||||
|
headers = [_("License"), _("Product / version"), _("Type"), _("Quantity"), _("Term"), _("Status"), _("Support"), _("Installed on"), _("Tenant")]
|
||||||
|
if show_key:
|
||||||
|
headers.append(_("License key"))
|
||||||
|
|
||||||
|
blocks = []
|
||||||
|
by_manufacturer = sorted(qs, key=lambda lic: (str(lic.software_product.manufacturer or "~"), str(lic.software_product), lic.name))
|
||||||
|
for manufacturer, items in groupby(by_manufacturer, key=lambda lic: lic.software_product.manufacturer):
|
||||||
|
rows = []
|
||||||
|
for lic in items:
|
||||||
|
period, status = _validity(lic, today)
|
||||||
|
product = str(lic.software_product) + (f" {lic.version}" if lic.version else "")
|
||||||
|
row = [
|
||||||
|
lic.name + (f"\n{lic.description}" if lic.description else ""),
|
||||||
|
product,
|
||||||
|
lic.type or lic.spdx_expression,
|
||||||
|
lic.license_amount,
|
||||||
|
period,
|
||||||
|
status,
|
||||||
|
_support(lic.support),
|
||||||
|
_installed_on(lic),
|
||||||
|
lic.tenant or lic.tenant_group,
|
||||||
|
]
|
||||||
|
if show_key:
|
||||||
|
row.append(lic.license_key)
|
||||||
|
rows.append(row)
|
||||||
|
blocks.append(H(2, str(manufacturer) if manufacturer else _("No manufacturer")))
|
||||||
|
blocks.append(T(headers, rows))
|
||||||
|
return blocks
|
||||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
|||||||
|
# Generated by Django 6.1.2 on 2026-10-26 20:23
|
||||||
|
|
||||||
|
import django.core.validators
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('netbox_customer_export', '0002_topologysymbol'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='brandingprofile',
|
||||||
|
name='accent_color',
|
||||||
|
field=models.CharField(default='2E75B6', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='brandingprofile',
|
||||||
|
name='footer_text',
|
||||||
|
field=models.CharField(blank=True, default="Confidential – for the customer's internal use only", max_length=300),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='brandingprofile',
|
||||||
|
name='header_text_color',
|
||||||
|
field=models.CharField(default='FFFFFF', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='brandingprofile',
|
||||||
|
name='label_bg_color',
|
||||||
|
field=models.CharField(default='DEEAF6', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='brandingprofile',
|
||||||
|
name='primary_color',
|
||||||
|
field=models.CharField(default='1F4E79', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='brandingprofile',
|
||||||
|
name='stripe_color',
|
||||||
|
field=models.CharField(default='F3F7FB', max_length=6, validators=[django.core.validators.RegexValidator('^[0-9A-Fa-f]{6}$', 'Expected a hex colour without #, e.g. 1F4E79')]),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
from django.core.validators import FileExtensionValidator, MaxValueValidator, MinValueValidator, RegexValidator
|
from django.core.validators import FileExtensionValidator, MaxValueValidator, MinValueValidator, RegexValidator
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
hex_color = RegexValidator(r"^[0-9A-Fa-f]{6}$", "Hex-Farbe ohne # erwartet, z.B. 1F4E79")
|
hex_color = RegexValidator(r"^[0-9A-Fa-f]{6}$", _("Expected a hex colour without #, e.g. 1F4E79"))
|
||||||
|
|
||||||
|
|
||||||
def _color(default, verbose_name):
|
def _color(default, verbose_name):
|
||||||
@@ -12,36 +13,36 @@ def _color(default, verbose_name):
|
|||||||
class BrandingProfile(models.Model):
|
class BrandingProfile(models.Model):
|
||||||
"""In NetBox gepflegtes Design-Profil (Alternative/Ergänzung zu PLUGINS_CONFIG['brandings'])."""
|
"""In NetBox gepflegtes Design-Profil (Alternative/Ergänzung zu PLUGINS_CONFIG['brandings'])."""
|
||||||
|
|
||||||
name = models.CharField(max_length=100, unique=True, verbose_name="Name")
|
name = models.CharField(max_length=100, unique=True, verbose_name=_("Name"))
|
||||||
is_default = models.BooleanField(default=False, verbose_name="Standardprofil")
|
is_default = models.BooleanField(default=False, verbose_name=_("Default profile"))
|
||||||
company_name = models.CharField(max_length=200, blank=True, verbose_name="Firmenname")
|
company_name = models.CharField(max_length=200, blank=True, verbose_name=_("Company name"))
|
||||||
footer_text = models.CharField(
|
footer_text = models.CharField(
|
||||||
max_length=300, blank=True, default="Vertraulich – nur für den internen Gebrauch des Kunden", verbose_name="Fußzeile"
|
max_length=300, blank=True, default="Confidential – for the customer's internal use only", verbose_name=_("Footer")
|
||||||
)
|
)
|
||||||
logo = models.ImageField(upload_to="customer-export/logos/", blank=True, verbose_name="Logo")
|
logo = models.ImageField(upload_to="customer-export/logos/", blank=True, verbose_name=_("Logo"))
|
||||||
primary_color = _color("1F4E79", "Primärfarbe")
|
primary_color = _color("1F4E79", _("Primary colour"))
|
||||||
accent_color = _color("2E75B6", "Akzentfarbe")
|
accent_color = _color("2E75B6", _("Accent colour"))
|
||||||
header_text_color = _color("FFFFFF", "Schrift Tabellenkopf")
|
header_text_color = _color("FFFFFF", _("Table header text"))
|
||||||
label_bg_color = _color("DEEAF6", "Hintergrund Beschriftungen")
|
label_bg_color = _color("DEEAF6", _("Label background"))
|
||||||
stripe_color = _color("F3F7FB", "Zebrastreifen")
|
stripe_color = _color("F3F7FB", _("Row stripes"))
|
||||||
font_family = models.CharField(max_length=100, default="Calibri", verbose_name="Schriftart")
|
font_family = models.CharField(max_length=100, default="Calibri", verbose_name=_("Font"))
|
||||||
font_size = models.PositiveSmallIntegerField(
|
font_size = models.PositiveSmallIntegerField(
|
||||||
default=10, validators=[MinValueValidator(7), MaxValueValidator(16)], verbose_name="Schriftgröße (pt)"
|
default=10, validators=[MinValueValidator(7), MaxValueValidator(16)], verbose_name=_("Font size (pt)")
|
||||||
)
|
)
|
||||||
docx_template = models.FileField(
|
docx_template = models.FileField(
|
||||||
upload_to="customer-export/templates/",
|
upload_to="customer-export/templates/",
|
||||||
blank=True,
|
blank=True,
|
||||||
validators=[FileExtensionValidator(["docx", "dotx"])],
|
validators=[FileExtensionValidator(["docx", "dotx"])],
|
||||||
verbose_name="Word-Vorlage",
|
verbose_name=_("Word template"),
|
||||||
)
|
)
|
||||||
docx_table_style = models.CharField(max_length=100, blank=True, verbose_name="Tabellenformatvorlage (Word)")
|
docx_table_style = models.CharField(max_length=100, blank=True, verbose_name=_("Table style (Word)"))
|
||||||
extra_css = models.TextField(blank=True, verbose_name="Zusätzliches CSS (PDF/HTML)")
|
extra_css = models.TextField(blank=True, verbose_name=_("Additional CSS (PDF/HTML)"))
|
||||||
last_updated = models.DateTimeField(auto_now=True)
|
last_updated = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering = ("-is_default", "name")
|
ordering = ("-is_default", "name")
|
||||||
verbose_name = "Branding-Profil"
|
verbose_name = _("branding profile")
|
||||||
verbose_name_plural = "Branding-Profile"
|
verbose_name_plural = _("branding profiles")
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
@@ -80,19 +81,19 @@ class TopologySymbol(models.Model):
|
|||||||
"""Topologie-Symbol für einen Gerätetyp oder eine Geräterolle (Gerätetyp hat Vorrang)."""
|
"""Topologie-Symbol für einen Gerätetyp oder eine Geräterolle (Gerätetyp hat Vorrang)."""
|
||||||
|
|
||||||
device_type = models.OneToOneField(
|
device_type = models.OneToOneField(
|
||||||
"dcim.DeviceType", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name="Gerätetyp"
|
"dcim.DeviceType", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name=_("Device type")
|
||||||
)
|
)
|
||||||
role = models.OneToOneField(
|
role = models.OneToOneField(
|
||||||
"dcim.DeviceRole", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name="Geräterolle"
|
"dcim.DeviceRole", on_delete=models.CASCADE, null=True, blank=True, related_name="+", verbose_name=_("Device role")
|
||||||
)
|
)
|
||||||
kind = models.CharField(max_length=20, blank=True, verbose_name="Symbol")
|
kind = models.CharField(max_length=20, blank=True, verbose_name=_("Symbol"))
|
||||||
icon = models.ImageField(upload_to="customer-export/symbols/", blank=True, verbose_name="Eigenes Icon")
|
icon = models.ImageField(upload_to="customer-export/symbols/", blank=True, verbose_name=_("Custom icon"))
|
||||||
last_updated = models.DateTimeField(auto_now=True)
|
last_updated = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering = ("device_type__model", "role__name")
|
ordering = ("device_type__model", "role__name")
|
||||||
verbose_name = "Topologie-Symbol"
|
verbose_name = _("topology symbol")
|
||||||
verbose_name_plural = "Topologie-Symbole"
|
verbose_name_plural = _("topology symbols")
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return str(self.device_type or self.role)
|
return str(self.device_type or self.role)
|
||||||
@@ -102,17 +103,17 @@ class TopologySymbol(models.Model):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def target_label(self):
|
def target_label(self):
|
||||||
return "Gerätetyp" if self.device_type_id else "Geräterolle"
|
return _("Device type") if self.device_type_id else _("Device role")
|
||||||
|
|
||||||
def get_kind_display(self):
|
def get_kind_display(self):
|
||||||
from .symbols import KIND_CHOICES
|
from .symbols import KIND_CHOICES
|
||||||
|
|
||||||
return dict(KIND_CHOICES).get(self.kind, "Automatisch")
|
return dict(KIND_CHOICES).get(self.kind, _("Automatic"))
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
|
|
||||||
if bool(self.device_type_id) == bool(self.role_id):
|
if bool(self.device_type_id) == bool(self.role_id):
|
||||||
raise ValidationError("Bitte genau einen Gerätetyp oder eine Geräterolle wählen.")
|
raise ValidationError(_("Select exactly one device type or one device role."))
|
||||||
if not self.kind and not self.icon:
|
if not self.kind and not self.icon:
|
||||||
raise ValidationError("Bitte ein Symbol wählen oder ein eigenes Icon hochladen.")
|
raise ValidationError(_("Select a symbol or upload a custom icon."))
|
||||||
@@ -1,19 +1,20 @@
|
|||||||
from netbox.plugins import PluginMenuButton, PluginMenuItem
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
from netbox.plugins import PluginMenu, PluginMenuButton, PluginMenuItem
|
||||||
|
|
||||||
menu_items = (
|
_items = (
|
||||||
PluginMenuItem(
|
PluginMenuItem(
|
||||||
link="plugins:netbox_customer_export:select",
|
link="plugins:netbox_customer_export:select",
|
||||||
link_text="Kundendokumentation",
|
link_text=_("Customer Documentation"),
|
||||||
permissions=["dcim.view_site"],
|
permissions=["dcim.view_site"],
|
||||||
),
|
),
|
||||||
PluginMenuItem(
|
PluginMenuItem(
|
||||||
link="plugins:netbox_customer_export:symbol_list",
|
link="plugins:netbox_customer_export:symbol_list",
|
||||||
link_text="Topologie-Symbole",
|
link_text=_("Topology Symbols"),
|
||||||
permissions=["netbox_customer_export.view_topologysymbol"],
|
permissions=["netbox_customer_export.view_topologysymbol"],
|
||||||
buttons=(
|
buttons=(
|
||||||
PluginMenuButton(
|
PluginMenuButton(
|
||||||
link="plugins:netbox_customer_export:symbol_add",
|
link="plugins:netbox_customer_export:symbol_add",
|
||||||
title="Hinzufügen",
|
title=_("Add"),
|
||||||
icon_class="mdi mdi-plus-thick",
|
icon_class="mdi mdi-plus-thick",
|
||||||
permissions=["netbox_customer_export.add_topologysymbol"],
|
permissions=["netbox_customer_export.add_topologysymbol"],
|
||||||
),
|
),
|
||||||
@@ -21,15 +22,25 @@ menu_items = (
|
|||||||
),
|
),
|
||||||
PluginMenuItem(
|
PluginMenuItem(
|
||||||
link="plugins:netbox_customer_export:branding_list",
|
link="plugins:netbox_customer_export:branding_list",
|
||||||
link_text="Branding-Profile",
|
link_text=_("Branding Profiles"),
|
||||||
permissions=["netbox_customer_export.view_brandingprofile"],
|
permissions=["netbox_customer_export.view_brandingprofile"],
|
||||||
buttons=(
|
buttons=(
|
||||||
PluginMenuButton(
|
PluginMenuButton(
|
||||||
link="plugins:netbox_customer_export:branding_add",
|
link="plugins:netbox_customer_export:branding_add",
|
||||||
title="Hinzufügen",
|
title=_("Add"),
|
||||||
icon_class="mdi mdi-plus-thick",
|
icon_class="mdi mdi-plus-thick",
|
||||||
permissions=["netbox_customer_export.add_brandingprofile"],
|
permissions=["netbox_customer_export.add_brandingprofile"],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Eigener Eintrag im obersten Navigationsmenü statt unter „Plugins“
|
||||||
|
menu = PluginMenu(
|
||||||
|
label=_("Customer Export"),
|
||||||
|
groups=(
|
||||||
|
(_("Export"), _items[:1]),
|
||||||
|
(_("Settings"), _items[1:]),
|
||||||
|
),
|
||||||
|
icon_class="mdi mdi-file-document-multiple-outline",
|
||||||
|
)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""Bildanhänge (extras.ImageAttachment) von Racks: Auswahl im Formular und Anhang am Dokumentende."""
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from dcim.models import Rack
|
||||||
|
from django.contrib.contenttypes.models import ContentType
|
||||||
|
from extras.models import ImageAttachment
|
||||||
|
|
||||||
|
MAX_EDGE = 1600 # px – Handyfotos verkleinern, damit PDF/Word handlich bleiben
|
||||||
|
|
||||||
|
|
||||||
|
def attachments(scope):
|
||||||
|
"""Bildanhänge aller Racks im Scope, die der Benutzer sehen darf – sortiert nach Rack."""
|
||||||
|
racks = {r.pk: r for r in scope.racks().select_related("site", "location")}
|
||||||
|
if not racks:
|
||||||
|
return []
|
||||||
|
qs = (
|
||||||
|
ImageAttachment.objects.restrict(scope.user, "view")
|
||||||
|
.filter(object_type=ContentType.objects.get_for_model(Rack), object_id__in=racks)
|
||||||
|
.order_by("name", "pk")
|
||||||
|
)
|
||||||
|
items = [(racks[a.object_id], a) for a in qs]
|
||||||
|
items.sort(key=lambda x: (str(x[0].site), str(x[0].location or ""), x[0].name))
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def grouped(scope):
|
||||||
|
"""[(rack, [attachment, …]), …] für die Vorschau im Formular."""
|
||||||
|
out = []
|
||||||
|
for rack, att in attachments(scope):
|
||||||
|
if out and out[-1][0] == rack:
|
||||||
|
out[-1][1].append(att)
|
||||||
|
else:
|
||||||
|
out.append((rack, [att]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def caption(att):
|
||||||
|
name = att.name or att.image.name.rsplit("/", 1)[-1]
|
||||||
|
desc = getattr(att, "description", "")
|
||||||
|
return f"{name} – {desc}" if desc else name
|
||||||
|
|
||||||
|
|
||||||
|
def load_jpeg(att):
|
||||||
|
"""Bild drehen (EXIF), verkleinern und als JPEG zurückgeben. None, wenn nicht lesbar."""
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
try:
|
||||||
|
with att.image.open("rb") as f:
|
||||||
|
img = Image.open(BytesIO(f.read()))
|
||||||
|
img = ImageOps.exif_transpose(img)
|
||||||
|
img.thumbnail((MAX_EDGE, MAX_EDGE))
|
||||||
|
if img.mode != "RGB":
|
||||||
|
img = img.convert("RGB")
|
||||||
|
out = BytesIO()
|
||||||
|
img.save(out, "JPEG", quality=85)
|
||||||
|
return out.getvalue()
|
||||||
|
except Exception: # noqa: BLE001 – fehlende/defekte Datei überspringen
|
||||||
|
return None
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
|
||||||
class MissingDependency(Exception):
|
class MissingDependency(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -18,6 +21,6 @@ def render(doc, fmt, request=None):
|
|||||||
try:
|
try:
|
||||||
from weasyprint import HTML
|
from weasyprint import HTML
|
||||||
except (ImportError, OSError) as e:
|
except (ImportError, OSError) as e:
|
||||||
raise MissingDependency(f"PDF-Export benötigt WeasyPrint (pip install weasyprint + Pango): {e}")
|
raise MissingDependency(_("PDF export requires WeasyPrint (pip install weasyprint + Pango): %(error)s") % {"error": e})
|
||||||
base_url = request.build_absolute_uri("/") if request else None
|
base_url = request.build_absolute_uri("/") if request else None
|
||||||
return HTML(string=html, base_url=base_url).write_pdf(), "application/pdf", "pdf"
|
return HTML(string=html, base_url=base_url).write_pdf(), "application/pdf", "pdf"
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
|
import re
|
||||||
import zipfile
|
import zipfile
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
from . import MissingDependency
|
from . import MissingDependency
|
||||||
|
|
||||||
DOTX_TYPE = b"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"
|
DOTX_TYPE = b"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"
|
||||||
@@ -18,6 +21,11 @@ def _svg_to_png(svg):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _bookmark_name(anchor):
|
||||||
|
"""Word-Textmarken: max. 40 Zeichen, Buchstabe vorne, nur Buchstaben/Ziffern/_."""
|
||||||
|
return ("_ce_" + re.sub(r"\W", "_", anchor))[:40]
|
||||||
|
|
||||||
|
|
||||||
def _load_template(path):
|
def _load_template(path):
|
||||||
"""Öffnet eine .docx/.dotx-Vorlage und leert deren Textkörper (Formatvorlagen, Kopf-/Fußzeile bleiben)."""
|
"""Öffnet eine .docx/.dotx-Vorlage und leert deren Textkörper (Formatvorlagen, Kopf-/Fußzeile bleiben)."""
|
||||||
from docx import Document as Docx
|
from docx import Document as Docx
|
||||||
@@ -46,7 +54,7 @@ def render_docx(doc):
|
|||||||
from docx.oxml.ns import qn
|
from docx.oxml.ns import qn
|
||||||
from docx.shared import Cm, Pt, RGBColor
|
from docx.shared import Cm, Pt, RGBColor
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
raise MissingDependency(f"Word-Export benötigt python-docx (pip install python-docx cairosvg): {e}")
|
raise MissingDependency(_("Word export requires python-docx (pip install python-docx cairosvg): %(error)s") % {"error": e})
|
||||||
|
|
||||||
b = doc.branding
|
b = doc.branding
|
||||||
primary = RGBColor.from_string(b["primary_color"])
|
primary = RGBColor.from_string(b["primary_color"])
|
||||||
@@ -56,11 +64,12 @@ def render_docx(doc):
|
|||||||
try:
|
try:
|
||||||
d = _load_template(template)
|
d = _load_template(template)
|
||||||
except (OSError, KeyError, zipfile.BadZipFile) as e:
|
except (OSError, KeyError, zipfile.BadZipFile) as e:
|
||||||
raise MissingDependency(f"Word-Vorlage {template!r} konnte nicht geladen werden: {e}")
|
raise MissingDependency(_("Word template %(path)r could not be loaded: %(error)s") % {"path": template, "error": e})
|
||||||
else:
|
else:
|
||||||
# Ohne Vorlage: Standarddokument mit Farben/Schrift aus dem Branding
|
# Ohne Vorlage: Standarddokument mit Farben/Schrift aus dem Branding
|
||||||
d = Docx()
|
d = Docx()
|
||||||
sec = d.sections[0]
|
sec = d.sections[0]
|
||||||
|
sec.page_width, sec.page_height = Cm(21), Cm(29.7) # A4 statt US-Letter aus der python-docx-Vorlage
|
||||||
sec.left_margin = sec.right_margin = Cm(2)
|
sec.left_margin = sec.right_margin = Cm(2)
|
||||||
sec.top_margin = sec.bottom_margin = Cm(2)
|
sec.top_margin = sec.bottom_margin = Cm(2)
|
||||||
d.styles["Normal"].font.name = b["font_family"]
|
d.styles["Normal"].font.name = b["font_family"]
|
||||||
@@ -91,7 +100,7 @@ def render_docx(doc):
|
|||||||
meta = doc.meta
|
meta = doc.meta
|
||||||
if b.get("logo_path"):
|
if b.get("logo_path"):
|
||||||
d.add_picture(b["logo_path"], width=Cm(5))
|
d.add_picture(b["logo_path"], width=Cm(5))
|
||||||
for _ in range(6):
|
for _blank in range(6):
|
||||||
d.add_paragraph()
|
d.add_paragraph()
|
||||||
title = d.add_paragraph()
|
title = d.add_paragraph()
|
||||||
run = title.add_run(doc.title)
|
run = title.add_run(doc.title)
|
||||||
@@ -101,13 +110,13 @@ def render_docx(doc):
|
|||||||
d.add_paragraph().add_run(doc.subtitle).font.size = Pt(16)
|
d.add_paragraph().add_run(doc.subtitle).font.size = Pt(16)
|
||||||
d.add_paragraph()
|
d.add_paragraph()
|
||||||
info = d.add_paragraph()
|
info = d.add_paragraph()
|
||||||
for label, value in (("Stand", meta.get("date")), ("Erstellt von", meta.get("author")), ("", b.get("company_name"))):
|
for label, value in ((_("As of"), meta.get("date")), (_("Created by"), meta.get("author")), ("", b.get("company_name"))):
|
||||||
if value:
|
if value:
|
||||||
info.add_run(f"{label + ': ' if label else ''}{value}\n")
|
info.add_run(f"{label + ': ' if label else ''}{value}\n")
|
||||||
d.add_page_break()
|
d.add_page_break()
|
||||||
|
|
||||||
# Inhaltsverzeichnis (wird beim Öffnen in Word aktualisiert)
|
# Inhaltsverzeichnis (wird beim Öffnen in Word aktualisiert)
|
||||||
d.add_heading("Inhaltsverzeichnis", level=1)
|
d.add_heading(_("Table of contents"), level=1)
|
||||||
fld = OxmlElement("w:fldSimple")
|
fld = OxmlElement("w:fldSimple")
|
||||||
fld.set(qn("w:instr"), 'TOC \\o "1-2" \\h \\z \\u')
|
fld.set(qn("w:instr"), 'TOC \\o "1-2" \\h \\z \\u')
|
||||||
d.add_paragraph()._p.append(fld)
|
d.add_paragraph()._p.append(fld)
|
||||||
@@ -116,11 +125,100 @@ def render_docx(doc):
|
|||||||
d.settings.element.append(upd)
|
d.settings.element.append(upd)
|
||||||
d.add_page_break()
|
d.add_page_break()
|
||||||
|
|
||||||
|
from docx.enum.section import WD_ORIENT, WD_SECTION
|
||||||
|
|
||||||
|
portrait = d.sections[-1]
|
||||||
|
portrait_size = (portrait.page_width, portrait.page_height)
|
||||||
|
landscape_open = False
|
||||||
|
|
||||||
|
portrait_margins = (
|
||||||
|
portrait.left_margin, portrait.right_margin, portrait.top_margin, portrait.bottom_margin,
|
||||||
|
portrait.header_distance, portrait.footer_distance,
|
||||||
|
)
|
||||||
|
|
||||||
|
def new_section(landscape):
|
||||||
|
s = d.add_section(WD_SECTION.NEW_PAGE)
|
||||||
|
w, h = portrait_size
|
||||||
|
s.orientation = WD_ORIENT.LANDSCAPE if landscape else WD_ORIENT.PORTRAIT
|
||||||
|
s.page_width, s.page_height = (h, w) if landscape else (w, h)
|
||||||
|
if not landscape: # Ränder der Hochformat-Seiten wiederherstellen
|
||||||
|
(s.left_margin, s.right_margin, s.top_margin, s.bottom_margin,
|
||||||
|
s.header_distance, s.footer_distance) = portrait_margins
|
||||||
|
return s
|
||||||
|
|
||||||
|
targets = {blk.anchor for blk in doc.blocks if blk.kind == "ref"}
|
||||||
|
bookmark_id = [0]
|
||||||
|
|
||||||
|
def add_bookmark(paragraph, anchor):
|
||||||
|
bookmark_id[0] += 1
|
||||||
|
start = OxmlElement("w:bookmarkStart")
|
||||||
|
start.set(qn("w:id"), str(bookmark_id[0]))
|
||||||
|
start.set(qn("w:name"), _bookmark_name(anchor))
|
||||||
|
end = OxmlElement("w:bookmarkEnd")
|
||||||
|
end.set(qn("w:id"), str(bookmark_id[0]))
|
||||||
|
paragraph._p.insert(1 if paragraph._p.pPr is not None else 0, start)
|
||||||
|
paragraph._p.append(end)
|
||||||
|
|
||||||
|
def add_link(paragraph, text, anchor):
|
||||||
|
link = OxmlElement("w:hyperlink")
|
||||||
|
link.set(qn("w:anchor"), _bookmark_name(anchor))
|
||||||
|
run = OxmlElement("w:r")
|
||||||
|
rpr = OxmlElement("w:rPr")
|
||||||
|
color = OxmlElement("w:color")
|
||||||
|
color.set(qn("w:val"), b["primary_color"])
|
||||||
|
underline = OxmlElement("w:u")
|
||||||
|
underline.set(qn("w:val"), "single")
|
||||||
|
rpr.append(color)
|
||||||
|
rpr.append(underline)
|
||||||
|
run.append(rpr)
|
||||||
|
t = OxmlElement("w:t")
|
||||||
|
t.text = text
|
||||||
|
t.set(qn("xml:space"), "preserve")
|
||||||
|
run.append(t)
|
||||||
|
link.append(run)
|
||||||
|
paragraph._p.append(link)
|
||||||
|
|
||||||
for blk in doc.blocks:
|
for blk in doc.blocks:
|
||||||
if blk.kind == "heading":
|
if landscape_open and blk.kind != "landscape":
|
||||||
d.add_heading(blk.text, level=min(blk.level, 4))
|
# erst beim nächsten Inhalt zurück ins Hochformat – vermeidet leere Seiten
|
||||||
|
new_section(landscape=False)
|
||||||
|
landscape_open = False
|
||||||
|
if blk.kind == "landscape":
|
||||||
|
s = new_section(landscape=True)
|
||||||
|
# schmale Ränder, damit die Topologie möglichst groß wird
|
||||||
|
s.left_margin = s.right_margin = Cm(0.7)
|
||||||
|
s.top_margin, s.bottom_margin = Cm(0.7), Cm(1.1)
|
||||||
|
s.header_distance, s.footer_distance = Cm(0.3), Cm(0.4)
|
||||||
|
landscape_open = True
|
||||||
|
for h in blk.rows:
|
||||||
|
heading = d.add_heading(h.text, level=h.level)
|
||||||
|
heading.paragraph_format.space_before = Pt(0)
|
||||||
|
heading.paragraph_format.space_after = Pt(2)
|
||||||
|
png = blk.images[0]["png"]
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
px_w, px_h = Image.open(BytesIO(png)).size
|
||||||
|
avail_w = s.page_width - s.left_margin - s.right_margin
|
||||||
|
avail_h = s.page_height - s.top_margin - s.bottom_margin - Cm(1.1 * len(blk.rows) + 0.6)
|
||||||
|
para = d.add_paragraph()
|
||||||
|
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
if px_w / px_h >= avail_w / avail_h:
|
||||||
|
para.add_run().add_picture(BytesIO(png), width=avail_w)
|
||||||
|
else:
|
||||||
|
para.add_run().add_picture(BytesIO(png), height=avail_h)
|
||||||
|
elif blk.kind == "heading":
|
||||||
|
heading = d.add_heading(blk.text, level=min(blk.level, 4))
|
||||||
|
if blk.anchor in targets:
|
||||||
|
add_bookmark(heading, blk.anchor)
|
||||||
elif blk.kind == "paragraph":
|
elif blk.kind == "paragraph":
|
||||||
d.add_paragraph(blk.text)
|
d.add_paragraph(blk.text)
|
||||||
|
elif blk.kind == "ref":
|
||||||
|
para = d.add_paragraph()
|
||||||
|
if blk.rows and blk.rows[0]:
|
||||||
|
para.add_run(blk.rows[0])
|
||||||
|
add_link(para, blk.text, blk.anchor)
|
||||||
|
for r in para.runs:
|
||||||
|
r.font.size = Pt(max(b["font_size"] - 1, 7))
|
||||||
elif blk.kind == "pagebreak":
|
elif blk.kind == "pagebreak":
|
||||||
d.add_page_break()
|
d.add_page_break()
|
||||||
elif blk.kind in ("table", "kv"):
|
elif blk.kind in ("table", "kv"):
|
||||||
@@ -160,10 +258,16 @@ def render_docx(doc):
|
|||||||
cell = t.cell(0, i).paragraphs[0]
|
cell = t.cell(0, i).paragraphs[0]
|
||||||
cell.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
cell.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
if png:
|
if png:
|
||||||
# Topologie: volle Breite; Racks: 7 cm (Höhe skaliert mit der Rackgröße)
|
# Topologie: volle Breite; Fotos: halbe Breite; Racks: 7 cm (Höhe skaliert mit der Rackgröße)
|
||||||
cell.add_run().add_picture(BytesIO(png), width=Cm(16.5 if blk.level == 1 else 7))
|
width = {1: 16.5, 2: 8}.get(blk.level, 7)
|
||||||
|
if blk.level == 2:
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
px_w, px_h = Image.open(BytesIO(png)).size
|
||||||
|
width = min(width, 9 * px_w / px_h) # Hochformat-Fotos auf max. 9 cm Höhe begrenzen
|
||||||
|
cell.add_run().add_picture(BytesIO(png), width=Cm(width))
|
||||||
else:
|
else:
|
||||||
cell.add_run("(Rack-Grafik nicht verfügbar)")
|
cell.add_run(_("(rack graphic not available)"))
|
||||||
cap = t.cell(1, i).paragraphs[0]
|
cap = t.cell(1, i).paragraphs[0]
|
||||||
cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
if img["caption"]:
|
if img["caption"]:
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
"""Ermittelt, welche Objekte zu einem Export-Scope (Standort, Lokation, Mandant, Mandantengruppe) gehören."""
|
"""Ermittelt, welche Objekte zu einem Export-Scope (Standort, Lokation, Mandant, Mandantengruppe) gehören."""
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
from circuits.models import Circuit
|
from circuits.models import Circuit
|
||||||
from dcim.models import Device, Location, PowerFeed, Rack, Site
|
from dcim.models import Device, Location, PowerFeed, Rack, Site
|
||||||
from ipam.models import VLAN, VRF, IPAddress, Prefix
|
from ipam.models import VLAN, VRF, IPAddress, Prefix
|
||||||
from tenancy.models import Tenant, TenantGroup
|
from tenancy.models import Tenant, TenantGroup
|
||||||
from virtualization.models import VirtualMachine
|
from virtualization.models import Cluster, VirtualMachine
|
||||||
from wireless.models import WirelessLAN
|
from wireless.models import WirelessLAN
|
||||||
|
|
||||||
SCOPE_MODELS = {
|
SCOPE_MODELS = {
|
||||||
@@ -16,10 +17,10 @@ SCOPE_MODELS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
SCOPE_LABELS = {
|
SCOPE_LABELS = {
|
||||||
"site": "Standort",
|
"site": _("Site"),
|
||||||
"location": "Lokation",
|
"location": _("Location"),
|
||||||
"tenant": "Mandant",
|
"tenant": _("Tenant"),
|
||||||
"tenantgroup": "Mandantengruppe",
|
"tenantgroup": _("Tenant group"),
|
||||||
}
|
}
|
||||||
|
|
||||||
NONE = Q(pk__in=[])
|
NONE = Q(pk__in=[])
|
||||||
@@ -81,6 +82,12 @@ class Scope:
|
|||||||
def devices(self):
|
def devices(self):
|
||||||
return self._qs(Device, site=("site",), location=("location",))
|
return self._qs(Device, site=("site",), location=("location",))
|
||||||
|
|
||||||
|
def clusters(self):
|
||||||
|
"""Cluster am Scope selbst oder mit Hosts/VMs im Scope."""
|
||||||
|
own = Cluster.objects.filter(self._q(site=("_site",), location=("_location",), tenant=("tenant",)))
|
||||||
|
q = Q(pk__in=own.values("pk")) | Q(pk__in=self.devices().values("cluster")) | Q(pk__in=self.virtual_machines().values("cluster"))
|
||||||
|
return self.restrict(Cluster.objects.filter(q).distinct())
|
||||||
|
|
||||||
def virtual_machines(self):
|
def virtual_machines(self):
|
||||||
return self._qs(
|
return self._qs(
|
||||||
VirtualMachine,
|
VirtualMachine,
|
||||||
|
|||||||
+322
-112
@@ -5,9 +5,12 @@ from itertools import groupby
|
|||||||
|
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
from django.utils.translation import gettext_lazy, ngettext
|
||||||
from netbox.plugins import get_plugin_config
|
from netbox.plugins import get_plugin_config
|
||||||
|
|
||||||
from .blocks import EMPTY, H, IMAGES, KV, P, PAGEBREAK, T, get
|
from .blocks import EMPTY, H, IMAGES, KV, LANDSCAPE, P, PAGEBREAK, REF, T, get
|
||||||
|
from . import hardware_utilities
|
||||||
from .rack_png import render_rack_png
|
from .rack_png import render_rack_png
|
||||||
from .rack_svg import render_rack_svg
|
from .rack_svg import render_rack_svg
|
||||||
|
|
||||||
@@ -35,76 +38,105 @@ def section(key, label, group, default=True, hint=""):
|
|||||||
|
|
||||||
# --- Gerätespalten (vom Techniker wählbar) ------------------------------------
|
# --- Gerätespalten (vom Techniker wählbar) ------------------------------------
|
||||||
|
|
||||||
def _rack_pos(d):
|
def ip_versions(opts):
|
||||||
|
"""Gewählte IP-Versionen als Menge {4, 6}. Ohne Formular (z.B. Vorschau) beide."""
|
||||||
|
versions = opts.get("ip_versions")
|
||||||
|
return {4, 6} if versions is None else {int(v) for v in versions}
|
||||||
|
|
||||||
|
|
||||||
|
def ip_text(ips, opts, sep=", "):
|
||||||
|
"""IP-Objekte gefiltert nach gewählter Version als Text."""
|
||||||
|
versions = ip_versions(opts)
|
||||||
|
return sep.join(str(ip.address) for ip in ips if ip and ip.address.version in versions) or None
|
||||||
|
|
||||||
|
|
||||||
|
def primary_ips(obj, opts, sep=", "):
|
||||||
|
"""Primäre IPv4 und/oder IPv6 eines Geräts oder einer VM, je nach Auswahl."""
|
||||||
|
return ip_text([obj.primary_ip4, obj.primary_ip6], opts, sep)
|
||||||
|
|
||||||
|
|
||||||
|
def num(value):
|
||||||
|
"""Decimal/float ohne überflüssige Nachkommastellen, deutsches Komma: 245, 2,5."""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = f"{value:f}"
|
||||||
|
if "." in text:
|
||||||
|
text = text.rstrip("0").rstrip(".")
|
||||||
|
return text.replace(".", ",")
|
||||||
|
|
||||||
|
|
||||||
|
def _rack_pos(d, o=None):
|
||||||
if not d.rack:
|
if not d.rack:
|
||||||
return None
|
return None
|
||||||
pos = f" / HE {d.position:g}" if d.position else ""
|
pos = " / " + _("U %(u)s") % {"u": num(d.position)} if d.position else ""
|
||||||
return f"{d.rack}{pos}"
|
return f"{d.rack}{pos}"
|
||||||
|
|
||||||
|
|
||||||
DEVICE_COLUMNS = OrderedDict(
|
DEVICE_COLUMNS = OrderedDict(
|
||||||
[
|
[
|
||||||
("name", ("Name", lambda d: d.name or str(d))),
|
("name", (gettext_lazy("Name"), lambda d, o: d.name or str(d))),
|
||||||
("model", ("Hersteller / Modell", lambda d: f"{d.device_type.manufacturer} {d.device_type.model}")),
|
("model", (gettext_lazy("Manufacturer / model"), lambda d, o: f"{d.device_type.manufacturer} {d.device_type.model}")),
|
||||||
("site", ("Standort", lambda d: d.site)),
|
("site", (gettext_lazy("Site"), lambda d, o: d.site)),
|
||||||
("location", ("Lokation", lambda d: d.location)),
|
("location", (gettext_lazy("Location"), lambda d, o: d.location)),
|
||||||
("rack", ("Rack / HE", _rack_pos)),
|
("rack", (gettext_lazy("Rack / U"), _rack_pos)),
|
||||||
("status", ("Status", lambda d: d.get_status_display())),
|
("status", (gettext_lazy("Status"), lambda d, o: d.get_status_display())),
|
||||||
("platform", ("Plattform / OS", lambda d: d.platform)),
|
("platform", (gettext_lazy("Platform / OS"), lambda d, o: d.platform)),
|
||||||
("primary_ip", ("Management-IP", lambda d: d.primary_ip.address if d.primary_ip else None)),
|
("primary_ip", (gettext_lazy("Management IP"), lambda d, o: primary_ips(d, o))),
|
||||||
("oob_ip", ("OOB-IP", lambda d: d.oob_ip.address if d.oob_ip else None)),
|
("oob_ip", (gettext_lazy("OOB IP"), lambda d, o: ip_text([d.oob_ip], o))),
|
||||||
("serial", ("Seriennummer", lambda d: d.serial)),
|
("serial", (gettext_lazy("Serial number"), lambda d, o: d.serial)),
|
||||||
("asset_tag", ("Inventarnr.", lambda d: d.asset_tag)),
|
("cpu", (gettext_lazy("CPU"), lambda d, o: hardware_utilities.cpu_text(d))),
|
||||||
("tenant", ("Mandant", lambda d: d.tenant)),
|
("ram", (gettext_lazy("RAM"), lambda d, o: hardware_utilities.ram_text(d))),
|
||||||
("description", ("Beschreibung", lambda d: d.description)),
|
("asset_tag", (gettext_lazy("Asset tag"), lambda d, o: d.asset_tag)),
|
||||||
|
("tenant", (gettext_lazy("Tenant"), lambda d, o: d.tenant)),
|
||||||
|
("description", (gettext_lazy("Description"), lambda d, o: d.description)),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
DEFAULT_DEVICE_COLUMNS = ["name", "model", "location", "rack", "primary_ip", "serial"]
|
DEFAULT_DEVICE_COLUMNS = ["name", "model", "location", "rack", "primary_ip", "serial"]
|
||||||
|
|
||||||
|
|
||||||
def _device_table(devices, columns):
|
def _device_table(devices, columns, opts):
|
||||||
cols = [DEVICE_COLUMNS[c] for c in columns if c in DEVICE_COLUMNS]
|
cols = [DEVICE_COLUMNS[c] for c in columns if c in DEVICE_COLUMNS]
|
||||||
return T([c[0] for c in cols], [[c[1](d) for c in cols] for d in devices])
|
return T([c[0] for c in cols], [[c[1](d, opts) for c in cols] for d in devices])
|
||||||
|
|
||||||
|
|
||||||
def _empty(opts, blocks, text="Keine Einträge vorhanden."):
|
def _empty(opts, blocks, text=None):
|
||||||
if opts.get("include_empty"):
|
if opts.get("include_empty"):
|
||||||
blocks.append(P(text))
|
blocks.append(P(text or _("No entries.")))
|
||||||
return blocks
|
return blocks
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
# --- Abschnitte -------------------------------------------------------------
|
# --- Abschnitte -------------------------------------------------------------
|
||||||
|
|
||||||
@section("overview", "Übersicht & Standortdaten", "Allgemein", hint="Kennzahlen, Adressen, Lokationsbaum")
|
@section("overview", gettext_lazy("Overview & site data"), gettext_lazy("General"), hint=gettext_lazy("Key figures, addresses, location tree"))
|
||||||
def overview(scope, opts):
|
def overview(scope, opts):
|
||||||
blocks = [H(1, "Übersicht")]
|
blocks = [H(1, _("Overview"))]
|
||||||
counts = [
|
counts = [
|
||||||
("Standorte", scope.sites().count()),
|
(_("Sites"), scope.sites().count()),
|
||||||
("Racks", scope.racks().count()),
|
(_("Racks"), scope.racks().count()),
|
||||||
("Geräte", scope.devices().count()),
|
(_("Devices"), scope.devices().count()),
|
||||||
("Virtuelle Maschinen", scope.virtual_machines().count()),
|
(_("Virtual machines"), scope.virtual_machines().count()),
|
||||||
("Präfixe", scope.prefixes().count()),
|
(_("Prefixes"), scope.prefixes().count()),
|
||||||
("VLANs", scope.vlans().count()),
|
(_("VLANs"), scope.vlans().count()),
|
||||||
("Leitungen", scope.circuits().count()),
|
(_("Circuits"), scope.circuits().count()),
|
||||||
]
|
]
|
||||||
blocks.append(KV([(f"{scope.label}", scope.obj)] + counts))
|
blocks.append(KV([(f"{scope.label}", scope.obj)] + counts))
|
||||||
if getattr(scope.obj, "description", ""):
|
if getattr(scope.obj, "description", ""):
|
||||||
blocks.append(P(scope.obj.description))
|
blocks.append(P(scope.obj.description))
|
||||||
|
|
||||||
for site in scope.sites().select_related("region", "group", "tenant"):
|
for site in scope.sites().select_related("region", "group", "tenant"):
|
||||||
blocks.append(H(2, f"Standort {site.name}"))
|
blocks.append(H(2, _("Site %(name)s") % {"name": site.name}))
|
||||||
blocks.append(
|
blocks.append(
|
||||||
KV(
|
KV(
|
||||||
[
|
[
|
||||||
("Status", site.get_status_display()),
|
(_("Status"), site.get_status_display()),
|
||||||
("Region", site.region),
|
(_("Region"), site.region),
|
||||||
("Mandant", site.tenant),
|
(_("Tenant"), site.tenant),
|
||||||
("Einrichtung", site.facility),
|
(_("Facility"), site.facility),
|
||||||
("Anschrift", site.physical_address),
|
(_("Physical address"), site.physical_address),
|
||||||
("Lieferanschrift", site.shipping_address),
|
(_("Shipping address"), site.shipping_address),
|
||||||
("Zeitzone", site.time_zone),
|
(_("Time zone"), site.time_zone),
|
||||||
("Beschreibung", site.description),
|
(_("Description"), site.description),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -112,20 +144,20 @@ def overview(scope, opts):
|
|||||||
if locs.exists():
|
if locs.exists():
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["Lokation", "Übergeordnet", "Status", "Beschreibung"],
|
[_("Location"), _("Parent"), _("Status"), _("Description")],
|
||||||
[[(" " * loc.level) + loc.name, loc.parent, loc.get_status_display(), loc.description] for loc in locs],
|
[[(" " * loc.level) + loc.name, loc.parent, loc.get_status_display(), loc.description] for loc in locs],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("contacts", "Ansprechpartner", "Allgemein", hint="Kontakte an Standorten, Lokationen, Mandanten")
|
@section("contacts", gettext_lazy("Contacts"), gettext_lazy("General"), hint=gettext_lazy("Contacts of sites, locations, tenants"))
|
||||||
def contacts(scope, opts):
|
def contacts(scope, opts):
|
||||||
ContactAssignment = apps.get_model("tenancy", "ContactAssignment")
|
ContactAssignment = apps.get_model("tenancy", "ContactAssignment")
|
||||||
targets = [
|
targets = [
|
||||||
(scope.sites(), "Standort"),
|
(scope.sites(), _("Site")),
|
||||||
(scope.location_objects(), "Lokation"),
|
(scope.location_objects(), _("Location")),
|
||||||
(scope.tenant_objects(), "Mandant"),
|
(scope.tenant_objects(), _("Tenant")),
|
||||||
]
|
]
|
||||||
rows = []
|
rows = []
|
||||||
for qs, label in targets:
|
for qs, label in targets:
|
||||||
@@ -137,39 +169,41 @@ def contacts(scope, opts):
|
|||||||
rows.append(
|
rows.append(
|
||||||
[f"{label}: {a.object}", a.contact.name, a.role, a.get_priority_display(), a.contact.phone, a.contact.email]
|
[f"{label}: {a.object}", a.contact.name, a.role, a.get_priority_display(), a.contact.phone, a.contact.email]
|
||||||
)
|
)
|
||||||
blocks = [H(1, "Ansprechpartner")]
|
blocks = [H(1, _("Contacts"))]
|
||||||
if not rows:
|
if not rows:
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
blocks.append(T(["Zuordnung", "Name", "Rolle", "Priorität", "Telefon", "E-Mail"], rows))
|
blocks.append(T([_("Assigned to"), _("Name"), _("Role"), _("Priority"), _("Phone"), _("Email")], rows))
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("racks", "Racks", "Infrastruktur", hint="Nach Standort & Lokation, mit Rack-Ansicht")
|
@section("racks", gettext_lazy("Racks"), gettext_lazy("Infrastructure"), hint=gettext_lazy("By site & location, with rack elevation"))
|
||||||
def racks(scope, opts):
|
def racks(scope, opts):
|
||||||
qs = (
|
qs = (
|
||||||
scope.racks()
|
scope.racks()
|
||||||
.select_related("site", "location", "role", "tenant", "rack_type")
|
.select_related("site", "location", "role", "tenant", "rack_type")
|
||||||
.order_by("site__name", "location__name", "name")
|
.order_by("site__name", "location__name", "name")
|
||||||
)
|
)
|
||||||
blocks = [H(1, "Racks")]
|
blocks = [H(1, _("Racks"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
|
photos = _rack_photos(scope, opts)
|
||||||
for site, site_racks in groupby(qs, key=lambda r: r.site):
|
for site, site_racks in groupby(qs, key=lambda r: r.site):
|
||||||
blocks.append(H(2, f"Standort {site}"))
|
blocks.append(H(2, _("Site %(name)s") % {"name": site}))
|
||||||
for location, loc_racks in groupby(site_racks, key=lambda r: r.location):
|
for location, loc_racks in groupby(site_racks, key=lambda r: r.location):
|
||||||
blocks.append(H(3, f"Lokation {location}" if location else "Ohne Lokation"))
|
blocks.append(H(3, _("Location %(name)s") % {"name": location} if location else _("No location")))
|
||||||
for rack in loc_racks:
|
for rack in loc_racks:
|
||||||
blocks.append(H(4, f"Rack {rack.name}"))
|
rack_heading = H(4, _("Rack %(name)s") % {"name": rack.name})
|
||||||
|
blocks.append(rack_heading)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
KV(
|
KV(
|
||||||
[
|
[
|
||||||
("Status", rack.get_status_display()),
|
(_("Status"), rack.get_status_display()),
|
||||||
("Rolle", rack.role),
|
(_("Role"), rack.role),
|
||||||
("Typ", rack.rack_type),
|
(_("Type"), rack.rack_type),
|
||||||
("Höhe", f"{rack.u_height} HE"),
|
(_("Height"), _("%(u)s U") % {"u": rack.u_height}),
|
||||||
("Facility-ID", rack.facility_id),
|
(_("Facility ID"), rack.facility_id),
|
||||||
("Mandant", rack.tenant),
|
(_("Tenant"), rack.tenant),
|
||||||
("Beschreibung", rack.description),
|
(_("Description"), rack.description),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -180,7 +214,7 @@ def racks(scope, opts):
|
|||||||
)
|
)
|
||||||
with_images = bool(opts.get("rack_images"))
|
with_images = bool(opts.get("rack_images"))
|
||||||
for face in opts.get("rack_faces") or ["front"]:
|
for face in opts.get("rack_faces") or ["front"]:
|
||||||
caption = "Vorderseite" if face == "front" else "Rückseite"
|
caption = _("Front") if face == "front" else _("Rear")
|
||||||
svg, svg_error = render_rack_svg(rack, face, scope.user, images=with_images, devices=rack_devs)
|
svg, svg_error = render_rack_svg(rack, face, scope.user, images=with_images, devices=rack_devs)
|
||||||
png = None
|
png = None
|
||||||
# PNG wird für Word gebraucht (falls kein cairosvg) und ersetzt ein fehlgeschlagenes SVG
|
# PNG wird für Word gebraucht (falls kein cairosvg) und ersetzt ein fehlgeschlagenes SVG
|
||||||
@@ -192,7 +226,7 @@ def racks(scope, opts):
|
|||||||
if svg or png:
|
if svg or png:
|
||||||
images.append((svg, caption, png))
|
images.append((svg, caption, png))
|
||||||
else:
|
else:
|
||||||
errors.append(f"Rack-Ansicht ({caption}) konnte nicht erzeugt werden: {svg_error}")
|
errors.append(_("Rack elevation (%(face)s) could not be created: %(error)s") % {"face": caption, "error": svg_error})
|
||||||
if images:
|
if images:
|
||||||
blocks.append(IMAGES(images))
|
blocks.append(IMAGES(images))
|
||||||
blocks += [P(e) for e in errors]
|
blocks += [P(e) for e in errors]
|
||||||
@@ -201,21 +235,61 @@ def racks(scope, opts):
|
|||||||
if devs.exists():
|
if devs.exists():
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["HE", "Gerät", "Hersteller / Modell", "Seite"],
|
[_("U"), _("Device"), _("Manufacturer / model"), _("Face")],
|
||||||
[
|
[
|
||||||
[f"{d.position:g}" if d.position else EMPTY, d.name, f"{d.device_type.manufacturer} {d.device_type.model}", d.get_face_display() if d.face else EMPTY]
|
[num(d.position) if d.position else EMPTY, d.name, f"{d.device_type.manufacturer} {d.device_type.model}", d.get_face_display() if d.face else EMPTY]
|
||||||
for d in devs
|
for d in devs
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
if rack.pk in photos:
|
||||||
|
blocks += _photo_appendix(opts, rack, rack_heading, photos[rack.pk])
|
||||||
if opts.get("rack_pagebreak"):
|
if opts.get("rack_pagebreak"):
|
||||||
blocks.append(PAGEBREAK())
|
blocks.append(PAGEBREAK())
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("devices", "Geräte", "Infrastruktur", hint="Tabellen je Geräterolle")
|
def _rack_photos(scope, opts):
|
||||||
|
"""Ausgewählte Bildanhänge je Rack-ID."""
|
||||||
|
selected = set(opts.get("rack_photos") or [])
|
||||||
|
if not selected:
|
||||||
|
return {}
|
||||||
|
from . import rack_photos
|
||||||
|
|
||||||
|
out = {}
|
||||||
|
for rack, att in rack_photos.attachments(scope):
|
||||||
|
if str(att.pk) in selected:
|
||||||
|
out.setdefault(rack.pk, []).append(att)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _photo_appendix(opts, rack, rack_heading, atts):
|
||||||
|
"""Legt die Fotos im Anhang ab (opts["_appendix"]) und liefert den Verweis unter der Rack-Ansicht."""
|
||||||
|
from . import rack_photos
|
||||||
|
|
||||||
|
images = [(None, rack_photos.caption(a), data) for a in atts if (data := rack_photos.load_jpeg(a))]
|
||||||
|
if not images:
|
||||||
|
return []
|
||||||
|
appendix = opts.setdefault("_appendix", [])
|
||||||
|
if not appendix:
|
||||||
|
appendix.append(H(1, _("Appendix: rack photos")))
|
||||||
|
where = " / ".join(str(x) for x in (rack.site, rack.location) if x)
|
||||||
|
heading = H(2, _("Rack %(name)s") % {"name": rack.name} + (f" ({where})" if where else ""))
|
||||||
|
appendix.append(heading)
|
||||||
|
for i in range(0, len(images), 2): # zwei Fotos je Zeile
|
||||||
|
appendix.append(IMAGES(images[i:i + 2], photos=True))
|
||||||
|
appendix.append(REF(_("Back to rack elevation"), rack_heading.anchor, prefix="↑ "))
|
||||||
|
n = len(images)
|
||||||
|
return [REF(
|
||||||
|
_("Appendix rack photos – rack %(name)s") % {"name": rack.name},
|
||||||
|
heading.anchor,
|
||||||
|
prefix=ngettext("%(n)d photo, see ", "%(n)d photos, see ", n) % {"n": n},
|
||||||
|
)]
|
||||||
|
|
||||||
|
|
||||||
|
@section("devices", gettext_lazy("Devices"), gettext_lazy("Infrastructure"), hint=gettext_lazy("Tables per device role"))
|
||||||
def devices(scope, opts):
|
def devices(scope, opts):
|
||||||
blocks = [H(1, "Geräte")]
|
blocks = [H(1, _("Devices"))]
|
||||||
base = scope.devices().select_related(
|
base = scope.devices().select_related(
|
||||||
"device_type__manufacturer", "role", "site", "location", "rack", "platform", "primary_ip4", "primary_ip6", "oob_ip", "tenant"
|
"device_type__manufacturer", "role", "site", "location", "rack", "platform", "primary_ip4", "primary_ip6", "oob_ip", "tenant"
|
||||||
)
|
)
|
||||||
@@ -229,114 +303,232 @@ def devices(scope, opts):
|
|||||||
blocks.append(H(2, role.name))
|
blocks.append(H(2, role.name))
|
||||||
if opts.get("group_by_site"):
|
if opts.get("group_by_site"):
|
||||||
for site, site_devs in groupby(devs, key=lambda d: d.site):
|
for site, site_devs in groupby(devs, key=lambda d: d.site):
|
||||||
blocks.append(H(3, f"Standort {site}"))
|
blocks.append(H(3, _("Site %(name)s") % {"name": site}))
|
||||||
blocks.append(_device_table(list(site_devs), columns))
|
blocks.append(_device_table(list(site_devs), columns, opts))
|
||||||
else:
|
else:
|
||||||
blocks.append(_device_table(devs, columns))
|
blocks.append(_device_table(devs, columns, opts))
|
||||||
return blocks if found else _empty(opts, blocks)
|
return blocks if found else _empty(opts, blocks)
|
||||||
|
|
||||||
|
|
||||||
@section("power", "Stromversorgung", "Infrastruktur", default=False, hint="Power Panels & Feeds")
|
@section("disks", gettext_lazy("Disks & RAID"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("From Netbox-Utilities (if installed)"))
|
||||||
|
def disks(scope, opts):
|
||||||
|
from . import disks_utilities
|
||||||
|
|
||||||
|
blocks = [H(1, _("Disks & RAID"))]
|
||||||
|
if not disks_utilities.is_installed():
|
||||||
|
return _empty(opts, blocks, _("No disks recorded."))
|
||||||
|
blocks += disks_utilities.disk_blocks(scope, opts)
|
||||||
|
return blocks if len(blocks) > 1 else _empty(opts, blocks)
|
||||||
|
|
||||||
|
|
||||||
|
@section("floorplans", gettext_lazy("Floor plans"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("From NetBox-FloorPlan (if installed)"))
|
||||||
|
def floorplans(scope, opts):
|
||||||
|
from . import floorplan
|
||||||
|
|
||||||
|
blocks = [H(1, _("Floor plans"))]
|
||||||
|
if not floorplan.is_installed():
|
||||||
|
return _empty(opts, blocks, _("No floor plans recorded."))
|
||||||
|
blocks += floorplan.floorplan_blocks(scope, opts)
|
||||||
|
return blocks if len(blocks) > 1 else _empty(opts, blocks, _("No floor plans recorded."))
|
||||||
|
|
||||||
|
|
||||||
|
@section("power", gettext_lazy("Power"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Power panels & feeds"))
|
||||||
def power(scope, opts):
|
def power(scope, opts):
|
||||||
qs = scope.power_feeds().select_related("power_panel", "rack").order_by("power_panel__name", "name")
|
qs = scope.power_feeds().select_related("power_panel", "rack").order_by("power_panel__name", "name")
|
||||||
blocks = [H(1, "Stromversorgung")]
|
blocks = [H(1, _("Power"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["Panel", "Feed", "Rack", "Status", "Typ", "Phase", "Spannung", "Ampere"],
|
[_("Panel"), _("Feed"), _("Rack"), _("Status"), _("Type"), _("Phase"), _("Voltage"), _("Amperage")],
|
||||||
[[f.power_panel, f.name, f.rack, get(f, "status"), get(f, "type"), get(f, "phase"), f"{f.voltage} V", f"{f.amperage} A"] for f in qs],
|
[[f.power_panel, f.name, f.rack, get(f, "status"), get(f, "type"), get(f, "phase"), f"{f.voltage} V", f"{f.amperage} A"] for f in qs],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("vms", "Virtuelle Maschinen", "Infrastruktur", default=False, hint="Cluster, Ressourcen, IP")
|
def _mb(value):
|
||||||
|
"""MB als lesbare Größe (VM-RAM/-Disk sind in NetBox in MB gespeichert)."""
|
||||||
|
if not value:
|
||||||
|
return EMPTY
|
||||||
|
for unit, size in (("TB", 1024 ** 2), ("GB", 1024)):
|
||||||
|
if value >= size:
|
||||||
|
return f"{value / size:.1f} {unit}".replace(".0 ", " ").replace(".", ",")
|
||||||
|
return f"{value} MB"
|
||||||
|
|
||||||
|
|
||||||
|
def _host_resources(hosts):
|
||||||
|
"""Summe der physischen Kerne, Threads und RAM (GB) aller Hosts mit gepflegter Hardware."""
|
||||||
|
cores = threads = ram = 0
|
||||||
|
for host in hosts:
|
||||||
|
hw = hardware_utilities.hardware(host)
|
||||||
|
c, t = hardware_utilities.cores_threads(hw)
|
||||||
|
cores, threads = cores + (c or 0), threads + (t or 0)
|
||||||
|
ram += (hw.memory_gb or 0) if hw else 0
|
||||||
|
return cores, threads, ram
|
||||||
|
|
||||||
|
|
||||||
|
def _vm_totals(vms):
|
||||||
|
return (
|
||||||
|
sum(vm.vcpus or 0 for vm in vms),
|
||||||
|
sum(vm.memory or 0 for vm in vms),
|
||||||
|
sum(vm.disk or 0 for vm in vms),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@section("clusters", gettext_lazy("Virtualization clusters"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Hosts and resources per cluster"))
|
||||||
|
def clusters(scope, opts):
|
||||||
|
qs = scope.clusters().select_related("type", "group", "tenant").order_by("group__name", "name")
|
||||||
|
blocks = [H(1, _("Virtualization clusters"))]
|
||||||
|
if not qs.exists():
|
||||||
|
return _empty(opts, blocks)
|
||||||
|
vms_by_cluster = {}
|
||||||
|
for vm in scope.virtual_machines().select_related("device"):
|
||||||
|
vms_by_cluster.setdefault(vm.cluster_id, []).append(vm)
|
||||||
|
|
||||||
|
summary, details = [], []
|
||||||
|
for cluster in qs:
|
||||||
|
vms = vms_by_cluster.get(cluster.pk, [])
|
||||||
|
hosts = list(scope.restrict(cluster.devices.all()).select_related("device_type__manufacturer").order_by("name"))
|
||||||
|
vcpu, ram, disk = _vm_totals(vms)
|
||||||
|
active = sum(1 for vm in vms if vm.status == "active")
|
||||||
|
p_cores, p_threads, p_ram = _host_resources(hosts)
|
||||||
|
ram_pct = f" ({round(ram / (p_ram * 1024) * 100)} %)" if ram and p_ram else ""
|
||||||
|
summary.append([
|
||||||
|
cluster.name, cluster.type, len(hosts), f"{active} / {len(vms)}",
|
||||||
|
f"{num(vcpu)} / {p_cores}" if vcpu and p_cores else num(vcpu) if vcpu else EMPTY,
|
||||||
|
f"{_mb(ram)} / {hardware_utilities.format_memory(p_ram)}" if ram and p_ram else _mb(ram),
|
||||||
|
_mb(disk),
|
||||||
|
])
|
||||||
|
|
||||||
|
details.append(H(2, _("Cluster %(name)s") % {"name": cluster.name}))
|
||||||
|
details.append(KV([
|
||||||
|
(_("Type"), cluster.type),
|
||||||
|
(_("Group"), cluster.group),
|
||||||
|
(_("Status"), get(cluster, "status")),
|
||||||
|
(_("Scope"), getattr(cluster, "scope", None)),
|
||||||
|
(_("Tenant"), cluster.tenant),
|
||||||
|
(_("Hosts"), len(hosts)),
|
||||||
|
(_("VMs active / total"), f"{active} / {len(vms)}"),
|
||||||
|
(_("Cores / threads (hosts)"), f"{p_cores} / {p_threads}" if p_cores else None),
|
||||||
|
(_("RAM (hosts)"), hardware_utilities.format_memory(p_ram) if p_ram else None),
|
||||||
|
(_("vCPU (total of VMs)"), num(vcpu) if vcpu else None),
|
||||||
|
(_("vCPU per core"), f"{num(round(float(vcpu) / p_cores, 1))} : 1" if vcpu and p_cores else None),
|
||||||
|
(_("RAM (total of VMs)"), (_mb(ram) + ram_pct) if ram else None),
|
||||||
|
(_("Storage (total)"), _mb(disk) if disk else None),
|
||||||
|
(_("Description"), cluster.description),
|
||||||
|
]))
|
||||||
|
if hosts:
|
||||||
|
rows = []
|
||||||
|
for host in hosts:
|
||||||
|
host_vms = [vm for vm in vms if vm.device_id == host.pk]
|
||||||
|
h_vcpu, h_ram, _h_disk = _vm_totals(host_vms)
|
||||||
|
h_cores, _t, h_pram = _host_resources([host])
|
||||||
|
rows.append([
|
||||||
|
host.name,
|
||||||
|
f"{host.device_type.manufacturer} {host.device_type.model}",
|
||||||
|
hardware_utilities.cpu_text(host),
|
||||||
|
hardware_utilities.format_memory(h_pram) if h_pram else None,
|
||||||
|
len(host_vms) if host_vms else EMPTY,
|
||||||
|
(f"{num(h_vcpu)} ({num(round(float(h_vcpu) / h_cores, 1))} : 1)" if h_cores else num(h_vcpu)) if h_vcpu else EMPTY,
|
||||||
|
(_mb(h_ram) + (f" ({round(h_ram / (h_pram * 1024) * 100)} %)" if h_pram else "")) if h_ram else EMPTY,
|
||||||
|
])
|
||||||
|
details.append(T([_("Host"), _("Manufacturer / model"), _("CPU"), _("RAM"), _("VMs"), _("vCPU"), _("RAM of VMs")], rows))
|
||||||
|
if any(vm.device_id is None for vm in vms):
|
||||||
|
details.append(P(_("VMs without a fixed host are only included in the cluster totals.")))
|
||||||
|
|
||||||
|
blocks.append(T([_("Cluster"), _("Type"), _("Hosts"), _("VMs active / total"), _("vCPU / cores"), _("RAM of VMs / hosts"), _("Storage")], summary))
|
||||||
|
return blocks + details
|
||||||
|
|
||||||
|
|
||||||
|
@section("vms", gettext_lazy("Virtual machines"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Cluster, resources, IP"))
|
||||||
def vms(scope, opts):
|
def vms(scope, opts):
|
||||||
qs = scope.virtual_machines().select_related("cluster", "role", "platform", "primary_ip4", "primary_ip6").order_by("cluster__name", "name")
|
qs = scope.virtual_machines().select_related("cluster", "role", "platform", "primary_ip4", "primary_ip6").order_by("cluster__name", "name")
|
||||||
blocks = [H(1, "Virtuelle Maschinen")]
|
blocks = [H(1, _("Virtual machines"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["Name", "Cluster", "Rolle", "Status", "OS", "vCPU", "RAM (MB)", "Disk (MB)", "IP"],
|
[_("Name"), _("Cluster"), _("Role"), _("Status"), _("OS"), "vCPU", _("RAM (MB)"), _("Disk (MB)"), "IP"],
|
||||||
[[vm.name, vm.cluster, vm.role, get(vm, "status"), vm.platform, vm.vcpus, vm.memory, vm.disk, vm.primary_ip.address if vm.primary_ip else None] for vm in qs],
|
[[vm.name, vm.cluster, vm.role, get(vm, "status"), vm.platform, vm.vcpus, vm.memory, vm.disk, primary_ips(vm, opts)] for vm in qs],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("vrfs", "VRFs", "Netzwerk", hint="Inkl. Route Targets")
|
@section("vrfs", gettext_lazy("VRFs"), gettext_lazy("Network"), hint=gettext_lazy("Including route targets"))
|
||||||
def vrfs(scope, opts):
|
def vrfs(scope, opts):
|
||||||
qs = scope.vrfs().select_related("tenant").prefetch_related("import_targets", "export_targets").order_by("name")
|
qs = scope.vrfs().select_related("tenant").prefetch_related("import_targets", "export_targets").order_by("name")
|
||||||
blocks = [H(1, "VRFs")]
|
blocks = [H(1, _("VRFs"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["Name", "RD", "Mandant", "Import-RT", "Export-RT", "Beschreibung"],
|
[_("Name"), "RD", _("Tenant"), _("Import RT"), _("Export RT"), _("Description")],
|
||||||
[[v.name, v.rd, v.tenant, v.import_targets, v.export_targets, v.description] for v in qs],
|
[[v.name, v.rd, v.tenant, v.import_targets, v.export_targets, v.description] for v in qs],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("prefixes", "IP-Netze", "Netzwerk", hint="Präfixe gruppiert nach VRF")
|
@section("prefixes", gettext_lazy("IP networks"), gettext_lazy("Network"), hint=gettext_lazy("Prefixes grouped by VRF"))
|
||||||
def prefixes(scope, opts):
|
def prefixes(scope, opts):
|
||||||
qs = scope.prefixes().select_related("vrf", "vlan", "role", "tenant").order_by("vrf__name", "prefix")
|
qs = scope.prefixes().select_related("vrf", "vlan", "role", "tenant").order_by("vrf__name", "prefix")
|
||||||
blocks = [H(1, "IP-Netze")]
|
qs = qs.filter(prefix__family__in=ip_versions(opts))
|
||||||
|
blocks = [H(1, _("IP networks"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
for vrf, items in groupby(qs, key=lambda p: p.vrf):
|
for vrf, items in groupby(qs, key=lambda p: p.vrf):
|
||||||
blocks.append(H(2, f"VRF {vrf}" if vrf else "Global"))
|
blocks.append(H(2, f"VRF {vrf}" if vrf else _("Global")))
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["Präfix", "VLAN", "Rolle", "Status", "Scope", "Beschreibung"],
|
[_("Prefix"), "VLAN", _("Role"), _("Status"), _("Scope"), _("Description")],
|
||||||
[[p.prefix, p.vlan, p.role, get(p, "status"), p.scope, p.description] for p in items],
|
[[p.prefix, p.vlan, p.role, get(p, "status"), p.scope, p.description] for p in items],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("vlans", "VLANs", "Netzwerk", hint="VID, Name, Gruppe, Rolle")
|
@section("vlans", gettext_lazy("VLANs"), gettext_lazy("Network"), hint=gettext_lazy("VID, name, group, role"))
|
||||||
def vlans(scope, opts):
|
def vlans(scope, opts):
|
||||||
qs = scope.vlans().select_related("group", "site", "role", "tenant").order_by("group__name", "vid")
|
qs = scope.vlans().select_related("group", "site", "role", "tenant").order_by("group__name", "vid")
|
||||||
blocks = [H(1, "VLANs")]
|
blocks = [H(1, _("VLANs"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["VID", "Name", "Gruppe", "Standort", "Rolle", "Status", "Beschreibung"],
|
["VID", _("Name"), _("Group"), _("Site"), _("Role"), _("Status"), _("Description")],
|
||||||
[[v.vid, v.name, v.group, v.site, v.role, get(v, "status"), v.description] for v in qs],
|
[[v.vid, v.name, v.group, v.site, v.role, get(v, "status"), v.description] for v in qs],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("ips", "IP-Adressen", "Netzwerk", default=False, hint="Ausführlich – kann lang werden")
|
@section("ips", gettext_lazy("IP addresses"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Detailed – can get long"))
|
||||||
def ips(scope, opts):
|
def ips(scope, opts):
|
||||||
qs = scope.ip_addresses().select_related("vrf", "tenant").prefetch_related("assigned_object").order_by("vrf__name", "address")
|
qs = scope.ip_addresses().select_related("vrf", "tenant").prefetch_related("assigned_object").order_by("vrf__name", "address")
|
||||||
blocks = [H(1, "IP-Adressen")]
|
qs = qs.filter(address__family__in=ip_versions(opts))
|
||||||
|
blocks = [H(1, _("IP addresses"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
for vrf, items in groupby(qs, key=lambda i: i.vrf):
|
for vrf, items in groupby(qs, key=lambda i: i.vrf):
|
||||||
blocks.append(H(2, f"VRF {vrf}" if vrf else "Global"))
|
blocks.append(H(2, f"VRF {vrf}" if vrf else _("Global")))
|
||||||
rows = []
|
rows = []
|
||||||
for ip in items:
|
for ip in items:
|
||||||
obj = ip.assigned_object
|
obj = ip.assigned_object
|
||||||
parent = getattr(obj, "parent_object", None)
|
parent = getattr(obj, "parent_object", None)
|
||||||
rows.append([ip.address, get(ip, "status"), get(ip, "role"), ip.dns_name, f"{parent} – {obj}" if parent else obj, ip.description])
|
rows.append([ip.address, get(ip, "status"), get(ip, "role"), ip.dns_name, f"{parent} – {obj}" if parent else obj, ip.description])
|
||||||
blocks.append(T(["Adresse", "Status", "Rolle", "DNS-Name", "Zugewiesen an", "Beschreibung"], rows))
|
blocks.append(T([_("Address"), _("Status"), _("Role"), _("DNS name"), _("Assigned to"), _("Description")], rows))
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("wireless", "WLANs", "Netzwerk", default=False, hint="SSIDs, Authentifizierung")
|
@section("wireless", gettext_lazy("Wireless LANs"), gettext_lazy("Network"), default=False, hint=gettext_lazy("SSIDs, authentication"))
|
||||||
def wireless(scope, opts):
|
def wireless(scope, opts):
|
||||||
qs = scope.wireless_lans().select_related("group", "vlan").order_by("ssid")
|
qs = scope.wireless_lans().select_related("group", "vlan").order_by("ssid")
|
||||||
blocks = [H(1, "WLANs")]
|
blocks = [H(1, _("Wireless LANs"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
headers = ["SSID", "Gruppe", "VLAN", "Status", "Authentifizierung", "Verschlüsselung"]
|
headers = ["SSID", _("Group"), "VLAN", _("Status"), _("Authentication"), _("Cipher")]
|
||||||
show_psk = opts.get("include_secrets")
|
show_psk = opts.get("include_secrets")
|
||||||
if show_psk:
|
if show_psk:
|
||||||
headers.append("PSK")
|
headers.append("PSK")
|
||||||
@@ -350,15 +542,15 @@ def wireless(scope, opts):
|
|||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
@section("circuits", "Leitungen", "Netzwerk", default=False, hint="Provider, Leitungs-ID, Bandbreite")
|
@section("circuits", gettext_lazy("Circuits"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Provider, circuit ID, bandwidth"))
|
||||||
def circuits(scope, opts):
|
def circuits(scope, opts):
|
||||||
qs = scope.circuits().select_related("provider", "type", "tenant").order_by("provider__name", "cid")
|
qs = scope.circuits().select_related("provider", "type", "tenant").order_by("provider__name", "cid")
|
||||||
blocks = [H(1, "Leitungen")]
|
blocks = [H(1, _("Circuits"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
T(
|
T(
|
||||||
["Leitungs-ID", "Provider", "Typ", "Status", "Bandbreite (Kbit/s)", "Beschreibung"],
|
[_("Circuit ID"), _("Provider"), _("Type"), _("Status"), _("Commit rate (Kbps)"), _("Description")],
|
||||||
[[c.cid, c.provider, c.type, get(c, "status"), c.commit_rate, c.description] for c in qs],
|
[[c.cid, c.provider, c.type, get(c, "status"), c.commit_rate, c.description] for c in qs],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -372,22 +564,27 @@ DEFAULT_LICENSE_SOURCES = [
|
|||||||
"model": "netbox_lifecycle.licenseassignment",
|
"model": "netbox_lifecycle.licenseassignment",
|
||||||
"device_field": "device",
|
"device_field": "device",
|
||||||
"columns": [
|
"columns": [
|
||||||
("Lizenz", "license"),
|
(gettext_lazy("License"), "license"),
|
||||||
("Hersteller", "license.manufacturer"),
|
(gettext_lazy("Manufacturer"), "license.manufacturer"),
|
||||||
("Gerät", "device"),
|
(gettext_lazy("Device"), "device"),
|
||||||
("Anzahl", "quantity"),
|
(gettext_lazy("Quantity"), "quantity"),
|
||||||
("Vertrag", "license.contract"),
|
(gettext_lazy("Contract"), "license.contract"),
|
||||||
("Beschreibung", "description"),
|
(gettext_lazy("Description"), "description"),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@section("licenses", "Lizenzen", "Verträge & Lizenzen", hint="Aus Lizenz-Plugin (z.B. netbox-lifecycle)")
|
@section("licenses", gettext_lazy("Licenses"), gettext_lazy("Contracts & licenses"), hint=gettext_lazy("From NetBox-SLM or another license plugin"))
|
||||||
def licenses(scope, opts):
|
def licenses(scope, opts):
|
||||||
|
from . import licenses_slm
|
||||||
|
|
||||||
sources = get_plugin_config("netbox_customer_export", "license_sources") or DEFAULT_LICENSE_SOURCES
|
sources = get_plugin_config("netbox_customer_export", "license_sources") or DEFAULT_LICENSE_SOURCES
|
||||||
blocks = [H(1, "Lizenzen")]
|
blocks = [H(1, _("Licenses"))]
|
||||||
found_source = False
|
found_source = False
|
||||||
|
if licenses_slm.is_installed():
|
||||||
|
found_source = True
|
||||||
|
blocks += licenses_slm.slm_blocks(scope, opts)
|
||||||
for src in sources:
|
for src in sources:
|
||||||
try:
|
try:
|
||||||
model = apps.get_model(src["model"])
|
model = apps.get_model(src["model"])
|
||||||
@@ -404,20 +601,33 @@ def licenses(scope, opts):
|
|||||||
cols = src["columns"]
|
cols = src["columns"]
|
||||||
blocks.append(T([c[0] for c in cols], [[get(o, c[1]) for c in cols] for o in qs]))
|
blocks.append(T([c[0] for c in cols], [[get(o, c[1]) for c in cols] for o in qs]))
|
||||||
if not found_source:
|
if not found_source:
|
||||||
return _empty(opts, blocks, "Kein Lizenz-Plugin installiert (z.B. netbox-lifecycle) – siehe README.")
|
return _empty(opts, blocks, _("No license plugin installed (NetBox-SLM or netbox-lifecycle) – see README."))
|
||||||
return blocks if len(blocks) > 1 else _empty(opts, blocks)
|
return blocks if len(blocks) > 1 else _empty(opts, blocks)
|
||||||
|
|
||||||
|
|
||||||
@section("topology", "Netzwerk-Topologie", "Netzwerk", default=False, hint="Diagramm mit Symbolen, wie Packet Tracer")
|
@section("topology", gettext_lazy("Network topology"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Diagram with symbols, like Packet Tracer"))
|
||||||
def topology(scope, opts):
|
def topology(scope, opts):
|
||||||
from .topology import build_graphs, render_png
|
from .topology import build_graphs, build_location_graphs, render_png
|
||||||
|
|
||||||
blocks = [H(1, "Netzwerk-Topologie")]
|
title = H(1, _("Network topology"))
|
||||||
graphs = build_graphs(scope, opts)
|
scopes = opts.get("topo_scope") or ["site"]
|
||||||
if not graphs:
|
|
||||||
return _empty(opts, blocks, "Keine verkabelten Geräte gefunden.")
|
|
||||||
ports = "ports" in (opts.get("topo_details") or [])
|
ports = "ports" in (opts.get("topo_details") or [])
|
||||||
for g in graphs:
|
pages = [] # (Überschriften, Graph) – je eine Querformat-Seite
|
||||||
blocks.append(H(2, g.title))
|
if "site" in scopes:
|
||||||
blocks.append(IMAGES([(None, "", render_png(g, show_ports=ports))], wide=True))
|
pages += [([H(2, g.title)], g) for g in build_graphs(scope, opts, per="site")]
|
||||||
return blocks
|
if "locations" in scopes:
|
||||||
|
locs = build_location_graphs(scope, opts)
|
||||||
|
pages += [(([H(2, _("Location overview"))] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(locs)]
|
||||||
|
if "locations_all" in scopes:
|
||||||
|
pages += [([H(2, _("Cross-site location overview"))], g) for g in build_location_graphs(scope, opts, combined=True)]
|
||||||
|
if "rack" in scopes:
|
||||||
|
racks = build_graphs(scope, opts, per="rack")
|
||||||
|
# Rack-Seiten unter einer gemeinsamen Zwischenüberschrift, Racks selbst eine Ebene tiefer (kürzeres Inhaltsverzeichnis)
|
||||||
|
pages += [(([H(2, _("Topology per rack"))] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(racks)]
|
||||||
|
if not pages:
|
||||||
|
return _empty(opts, [title], _("No cabled devices found."))
|
||||||
|
# Die Abschnittsüberschrift steht mit auf der ersten Seite
|
||||||
|
return [
|
||||||
|
LANDSCAPE(([title] if i == 0 else []) + headings, render_png(g, show_ports=ports))
|
||||||
|
for i, (headings, g) in enumerate(pages)
|
||||||
|
]
|
||||||
@@ -4,6 +4,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMix
|
|||||||
from django.http import Http404, HttpResponse
|
from django.http import Http404, HttpResponse
|
||||||
from django.shortcuts import get_object_or_404, redirect, render
|
from django.shortcuts import get_object_or_404, redirect, render
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
from django.views import View
|
from django.views import View
|
||||||
|
|
||||||
from .forms import TopologySymbolForm
|
from .forms import TopologySymbolForm
|
||||||
@@ -75,7 +76,7 @@ class SymbolEditView(PermissionRequiredMixin, View):
|
|||||||
form = TopologySymbolForm(request.POST, request.FILES, instance=obj)
|
form = TopologySymbolForm(request.POST, request.FILES, instance=obj)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
obj = form.save()
|
obj = form.save()
|
||||||
messages.success(request, f"Topologie-Symbol für „{obj}“ gespeichert.")
|
messages.success(request, _("Topology symbol for “%(name)s” saved.") % {"name": obj})
|
||||||
return redirect(f"plugins:{APP}:symbol_list")
|
return redirect(f"plugins:{APP}:symbol_list")
|
||||||
return self._render(request, obj, form)
|
return self._render(request, obj, form)
|
||||||
|
|
||||||
@@ -92,5 +93,5 @@ class SymbolDeleteView(PermissionRequiredMixin, View):
|
|||||||
if obj.icon:
|
if obj.icon:
|
||||||
obj.icon.delete(save=False)
|
obj.icon.delete(save=False)
|
||||||
obj.delete()
|
obj.delete()
|
||||||
messages.success(request, f"Topologie-Symbol für „{name}“ gelöscht – es gilt wieder die automatische Erkennung.")
|
messages.success(request, _("Topology symbol for “%(name)s” deleted – automatic detection applies again.") % {"name": name})
|
||||||
return redirect(f"plugins:{APP}:symbol_list")
|
return redirect(f"plugins:{APP}:symbol_list")
|
||||||
@@ -4,61 +4,84 @@ from collections import OrderedDict
|
|||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
# Schlüssel -> (Bezeichnung, Ebene im Diagramm; kleiner = weiter oben)
|
# Schlüssel -> (Bezeichnung, Ebene im Diagramm; kleiner = weiter oben)
|
||||||
KINDS = OrderedDict(
|
KINDS = OrderedDict(
|
||||||
[
|
[
|
||||||
("cloud", ("Internet / Provider", 0)),
|
("cloud", (_("Internet / provider"), 0)),
|
||||||
("firewall", ("Firewall", 1)),
|
("location", (_("Location / distribution"), 3)),
|
||||||
("router", ("Router", 1)),
|
("modem", (_("Modem / NTU / media converter"), 1)),
|
||||||
("l3switch", ("Layer-3-Switch / Core", 2)),
|
("firewall", (_("Firewall"), 1)),
|
||||||
("switch", ("Switch", 3)),
|
("router", (_("Router"), 1)),
|
||||||
("wlc", ("WLAN-Controller", 3)),
|
("l3switch", (_("Layer 3 switch / core"), 2)),
|
||||||
("ap", ("Access Point", 4)),
|
("switch", (_("Switch"), 3)),
|
||||||
("server", ("Server", 4)),
|
("radio", (_("Radio link / microwave"), 3)),
|
||||||
("storage", ("Storage / NAS", 4)),
|
("patchpanel", (_("Patch panel / distribution frame"), 3)),
|
||||||
("pc", ("PC / Client", 4)),
|
("wlc", (_("Wireless controller"), 3)),
|
||||||
("phone", ("IP-Telefon", 4)),
|
("poe", (_("PoE injector"), 4)),
|
||||||
("printer", ("Drucker", 4)),
|
("ap", (_("Access point"), 4)),
|
||||||
("camera", ("Kamera", 4)),
|
("server", (_("Server"), 4)),
|
||||||
("generic", ("Sonstiges Gerät", 4)),
|
("storage", (_("Storage / SAN (MSA)"), 4)),
|
||||||
|
("nas", (_("NAS"), 4)),
|
||||||
|
("tape", (_("Tape drive / tape library"), 4)),
|
||||||
|
("ups", (_("UPS / ATS"), 4)),
|
||||||
|
("pbx", (_("Phone system (PBX)"), 4)),
|
||||||
|
("phone", (_("IP phone"), 4)),
|
||||||
|
("pc", (_("PC / client"), 4)),
|
||||||
|
("printer", (_("Printer"), 4)),
|
||||||
|
("camera", (_("Camera"), 4)),
|
||||||
|
("generic", (_("Other device"), 4)),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
HIDDEN = "hidden"
|
HIDDEN = "hidden"
|
||||||
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k != "cloud"] + [(HIDDEN, "In Topologie ausblenden")]
|
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k not in ("cloud", "location")] + [(HIDDEN, _("Hide in topology"))]
|
||||||
|
|
||||||
# Reihenfolge wichtig: erster Treffer gewinnt. None = passiv, nicht zeichnen.
|
# Reihenfolge wichtig: erster Treffer gewinnt. None = passiv, nicht zeichnen.
|
||||||
|
# Tippvarianten („Acces Point“, „Controler“, „Libary“) sind absichtlich mit abgedeckt.
|
||||||
_RULES = [
|
_RULES = [
|
||||||
(r"patch|panel|pdu|steckdose|power|strom|kabel|cable|blank|blind|shelf|fachboden|ups|usv|rangier", None),
|
(r"patch|panel|\bpdu\b|steckdose|kabel|cable|blank|blind|shelf|fachboden|rangier|\braum\b|\broom\b|halterung|\bmount", None),
|
||||||
|
(r"\busv\b|\bups\b|\bats\b|smart-?ups|eaton|\bapc\b|online usv", "ups"),
|
||||||
|
(r"poe|injector|injektor", "poe"),
|
||||||
|
(r"funk|richtfunk|\bbridge\b|airmax|nanobeam|litebeam|powerbeam|\bptp\b|\bptmp\b|airfiber|siklu", "radio"),
|
||||||
|
(r"\brad\b|modem|\bntu\b|\bnt\b|\bont\b|media ?conver|medienkonverter|konverter|\betx-", "modem"),
|
||||||
(r"firewall|\bfw\b|fw-|sophos|fortigate|fortinet|palo ?alto|\butm\b|\bxgs\b|\bxg\b|watchguard|checkpoint|opnsense|pfsense", "firewall"),
|
(r"firewall|\bfw\b|fw-|sophos|fortigate|fortinet|palo ?alto|\butm\b|\bxgs\b|\bxg\b|watchguard|checkpoint|opnsense|pfsense", "firewall"),
|
||||||
(r"router|\brtr\b|gateway|\bgw\b|lancom|draytek|fritz|isr\d|asr\d|mikrotik", "router"),
|
(r"router|\brtr\b|gateway|\bgw\b|lancom|draytek|fritz|isr\d|asr\d|mikrotik", "router"),
|
||||||
(r"controller|\bwlc\b|mobility", "wlc"),
|
(r"control+er|\bwlc\b|mobility", "wlc"),
|
||||||
(r"access ?point|accesspoint|\bap\b|\bap-|-ap\b|\bwap\b|wlan|wifi|aironet|unifi ?ap|\biap\b|instant on ap", "ap"),
|
(r"acc?ess? ?point|\bap\b|\bap-|-ap\b|\bwap\b|wlan|wifi|aironet|unifi ?ap|\biap\b", "ap"),
|
||||||
(r"\bcore\b|\bl3\b|layer ?3|distribution|\bdist\b|backbone", "l3switch"),
|
(r"\bcore\b|\bl3\b|layer ?3|distribution|\bdist\b|backbone", "l3switch"),
|
||||||
(r"switch|\bsw\b|\bsw-|-sw\b|catalyst|aruba \d{4}|procurve|\bcbs\d|\bsg\d", "switch"),
|
(r"switch|\bsw\b|\bsw-|-sw\b|catalyst|aruba \d{4}|procurve|\bcbs\d|\bsg\d", "switch"),
|
||||||
(r"storage|\bnas\b|\bsan\b|synology|qnap|netapp", "storage"),
|
(r"tape|band|\blto\b|libr?ary|storeever|\bmsl\d", "tape"),
|
||||||
(r"server|\besx|hyper-?v|\bhost\b|proliant|poweredge|\bsrv\b|\bvm-?host", "server"),
|
(r"\bnas\b|diskstation|synology|qnap|terastation|readynas|\btvs-|\bds\d{3,4}", "nas"),
|
||||||
(r"telefon|phone|\bvoip\b|yealink|snom|gigaset", "phone"),
|
(r"storage|\bsan\b|\bmsa\b|netapp|powervault|eternus|\bme\d{4}", "storage"),
|
||||||
|
(r"server|\besx|hyper-?v|\bhost\b|proliant|poweredge|primergy|\bsrv\b|\bvm-?host", "server"),
|
||||||
|
(r"telefonanlage|\bpbx\b|\btk-?anlage|starface|3cx|innovaphone|agfeo|auerswald|unify|openscape", "pbx"),
|
||||||
|
(r"telefon|phone|\bvoip\b|yealink|snom|gigaset|grandstream", "phone"),
|
||||||
(r"drucker|printer|\bmfp\b|kyocera|brother|ricoh", "printer"),
|
(r"drucker|printer|\bmfp\b|kyocera|brother|ricoh", "printer"),
|
||||||
(r"kamera|camera|\bcam\b|axis|hikvision|dahua", "camera"),
|
(r"kamera|camera|\bcam\b|axis|hikvision|dahua", "camera"),
|
||||||
(r"\bpc\b|client|workstation|laptop|notebook|thin ?client|desktop", "pc"),
|
(r"\bpc\b|client|workstation|laptop|notebook|thin ?client|desktop", "pc"),
|
||||||
|
(r"sonstig|other|misc", "generic"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def guess_kind(device):
|
def _match(text):
|
||||||
"""Symbol aus Rolle, Gerätetyp und Hersteller raten. None = passives Gerät (nicht zeichnen)."""
|
"""(True, kind) beim ersten Treffer, sonst (False, None)."""
|
||||||
dt = device.device_type
|
text = text.lower()
|
||||||
role = device.role
|
|
||||||
text = " ".join(
|
|
||||||
str(x or "")
|
|
||||||
for x in (
|
|
||||||
getattr(role, "slug", ""), getattr(role, "name", ""),
|
|
||||||
dt.model, dt.slug, getattr(dt.manufacturer, "name", ""),
|
|
||||||
)
|
|
||||||
).lower()
|
|
||||||
for pattern, kind in _RULES:
|
for pattern, kind in _RULES:
|
||||||
if re.search(pattern, text):
|
if re.search(pattern, text):
|
||||||
return kind
|
return True, kind
|
||||||
return "generic"
|
return False, None
|
||||||
|
|
||||||
|
|
||||||
|
def guess_kind(device):
|
||||||
|
"""Symbol raten: zuerst anhand der Rolle, dann Modell/Hersteller. None = passives Gerät (nicht zeichnen)."""
|
||||||
|
role = device.role
|
||||||
|
found, kind = _match(f"{getattr(role, 'name', '')} {getattr(role, 'slug', '')}")
|
||||||
|
if found:
|
||||||
|
return kind
|
||||||
|
dt = device.device_type
|
||||||
|
found, kind = _match(f"{dt.model} {dt.slug} {getattr(dt.manufacturer, 'name', '')}")
|
||||||
|
return kind if found else "generic"
|
||||||
|
|
||||||
|
|
||||||
# --- Zeichnen -----------------------------------------------------------------
|
# --- Zeichnen -----------------------------------------------------------------
|
||||||
@@ -210,6 +233,91 @@ def _draw_generic(d):
|
|||||||
d.rectangle([26 + i * 18, 76, 38 + i * 18, 86], fill=(200, 208, 216))
|
d.rectangle([26 + i * 18, 76, 38 + i * 18, 86], fill=(200, 208, 216))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_modem(d):
|
||||||
|
# flache Box mit LED-Reihe und Glasfaser-/Leitungsanschluss (Modem, NTU, RAD, Medienkonverter)
|
||||||
|
_iso_box(d, 12, 58, 100, 88, 12, (70, 84, 100), (130, 146, 162), (52, 64, 78))
|
||||||
|
for i, c in enumerate(((60, 200, 90), (60, 200, 90), (250, 190, 40), (60, 200, 90))):
|
||||||
|
d.ellipse([22 + i * 12, 68, 28 + i * 12, 74], fill=c)
|
||||||
|
d.rectangle([76, 66, 92, 80], fill=(30, 36, 44))
|
||||||
|
d.line([(84, 58), (84, 34), (112, 34)], fill=(250, 170, 30), width=4)
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_radio(d):
|
||||||
|
# Richtfunk-Antenne auf Mast mit Funkwellen
|
||||||
|
d.rectangle([58, 64, 66, 116], fill=(120, 128, 138), outline=OUTLINE)
|
||||||
|
d.rectangle([40, 112, 84, 118], fill=(120, 128, 138), outline=OUTLINE)
|
||||||
|
d.ellipse([22, 26, 70, 90], fill=(236, 240, 244), outline=OUTLINE, width=3)
|
||||||
|
d.ellipse([36, 44, 56, 72], fill=(200, 208, 216), outline=OUTLINE, width=2)
|
||||||
|
for r in (14, 24, 34):
|
||||||
|
d.arc([74 - r, 58 - r, 74 + r, 58 + r], start=-50, end=50, fill=BLUE, width=5)
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_poe(d):
|
||||||
|
# kleine Box mit Blitz
|
||||||
|
_iso_box(d, 24, 50, 96, 98, 12, (58, 70, 84), (120, 134, 150), (42, 52, 64))
|
||||||
|
d.polygon([(66, 56), (48, 78), (60, 78), (54, 94), (76, 70), (63, 70), (70, 56)], fill=(250, 200, 40), outline=(160, 110, 0))
|
||||||
|
d.rectangle([30, 86, 40, 92], fill=(180, 190, 200))
|
||||||
|
d.rectangle([80, 86, 90, 92], fill=(180, 190, 200))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_nas(d):
|
||||||
|
# kompakte Box mit vier senkrechten Laufwerksschächten
|
||||||
|
_iso_box(d, 22, 30, 98, 108, 12, (54, 60, 70), (110, 118, 130), (38, 44, 52))
|
||||||
|
for i in range(4):
|
||||||
|
x = 30 + i * 17
|
||||||
|
d.rounded_rectangle([x, 40, x + 12, 96], radius=2, fill=(150, 158, 168))
|
||||||
|
d.ellipse([x + 4, 88, x + 8, 92], fill=(60, 200, 90))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_tape(d):
|
||||||
|
# Laufwerk mit Kassettenschacht, davor eine LTO-Kassette
|
||||||
|
_iso_box(d, 10, 44, 102, 82, 12, (84, 98, 112), (150, 162, 176), (60, 72, 84))
|
||||||
|
d.rectangle([22, 56, 72, 64], fill=(24, 28, 34))
|
||||||
|
d.ellipse([84, 56, 92, 64], fill=(60, 200, 90))
|
||||||
|
d.rounded_rectangle([36, 84, 92, 118], radius=4, fill=(40, 44, 50), outline=OUTLINE, width=2)
|
||||||
|
d.rectangle([44, 90, 84, 100], fill=(250, 190, 40))
|
||||||
|
d.ellipse([52, 104, 62, 114], fill=(150, 158, 168))
|
||||||
|
d.ellipse([68, 104, 78, 114], fill=(150, 158, 168))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_ups(d):
|
||||||
|
# Tower mit Batterie-Symbol
|
||||||
|
_iso_box(d, 32, 22, 88, 112, 12, (52, 58, 66), (110, 118, 128), (36, 42, 50))
|
||||||
|
d.rounded_rectangle([42, 36, 78, 60], radius=3, fill=(30, 36, 44))
|
||||||
|
d.rectangle([46, 42, 70, 54], outline=(60, 200, 90), width=2)
|
||||||
|
d.rectangle([70, 45, 74, 51], fill=(60, 200, 90))
|
||||||
|
d.rectangle([48, 44, 62, 52], fill=(60, 200, 90))
|
||||||
|
d.polygon([(62, 70), (50, 88), (58, 88), (54, 102), (70, 82), (62, 82), (68, 70)], fill=(250, 200, 40))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_patchpanel(d):
|
||||||
|
# flaches 19"-Feld mit zwei Portreihen, bewusst nüchtern (passives Element)
|
||||||
|
_iso_box(d, 8, 58, 104, 92, 14, (96, 104, 114), (150, 158, 168), (74, 82, 92))
|
||||||
|
for row in (64, 78):
|
||||||
|
for i in range(12):
|
||||||
|
d.rectangle([14 + i * 7.5, row, 19 + i * 7.5, row + 7], fill=(40, 46, 54))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_location(d):
|
||||||
|
# Verteilerschrank mit Glastür und Höheneinheiten – steht in der Übersicht für eine ganze Lokation
|
||||||
|
_iso_box(d, 26, 20, 92, 116, 12, (58, 74, 92), (118, 136, 156), (42, 56, 72))
|
||||||
|
d.rectangle([33, 27, 85, 109], fill=(170, 196, 220), outline=OUTLINE, width=2)
|
||||||
|
for i, y in enumerate(range(33, 101, 11)):
|
||||||
|
d.rectangle([38, y, 80, y + 7], fill=(40, 52, 66))
|
||||||
|
d.ellipse([74, y + 2, 77, y + 5], fill=(60, 200, 90) if i % 2 == 0 else (86, 149, 206))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_pbx(d):
|
||||||
|
# Anlage (Box) mit Hörer-Symbol
|
||||||
|
_iso_box(d, 12, 50, 104, 104, 12, (62, 70, 80), (126, 136, 148), (44, 52, 60))
|
||||||
|
d.rounded_rectangle([34, 62, 82, 92], radius=12, fill=(236, 240, 244))
|
||||||
|
d.rounded_rectangle([40, 70, 50, 86], radius=4, fill=(40, 44, 50))
|
||||||
|
d.rounded_rectangle([66, 70, 76, 86], radius=4, fill=(40, 44, 50))
|
||||||
|
d.rectangle([46, 70, 70, 76], fill=(40, 44, 50))
|
||||||
|
for i in range(3):
|
||||||
|
d.ellipse([88, 60 + i * 12, 96, 68 + i * 12], fill=(60, 200, 90))
|
||||||
|
|
||||||
|
|
||||||
_DRAWERS = {
|
_DRAWERS = {
|
||||||
"router": _draw_router,
|
"router": _draw_router,
|
||||||
"switch": _draw_switch,
|
"switch": _draw_switch,
|
||||||
@@ -225,6 +333,15 @@ _DRAWERS = {
|
|||||||
"camera": _draw_camera,
|
"camera": _draw_camera,
|
||||||
"cloud": _draw_cloud,
|
"cloud": _draw_cloud,
|
||||||
"generic": _draw_generic,
|
"generic": _draw_generic,
|
||||||
|
"modem": _draw_modem,
|
||||||
|
"radio": _draw_radio,
|
||||||
|
"poe": _draw_poe,
|
||||||
|
"nas": _draw_nas,
|
||||||
|
"tape": _draw_tape,
|
||||||
|
"ups": _draw_ups,
|
||||||
|
"pbx": _draw_pbx,
|
||||||
|
"patchpanel": _draw_patchpanel,
|
||||||
|
"location": _draw_location,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -272,6 +389,11 @@ class SymbolResolver:
|
|||||||
pass
|
pass
|
||||||
self._icons = {}
|
self._icons = {}
|
||||||
|
|
||||||
|
def is_hidden(self, device):
|
||||||
|
"""Per Symbolzuordnung ausdrücklich ausgeblendet?"""
|
||||||
|
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
|
||||||
|
return bool(sym and sym.kind == HIDDEN)
|
||||||
|
|
||||||
def resolve(self, device):
|
def resolve(self, device):
|
||||||
"""(kind, icon_png_bytes) oder (None, None), wenn das Gerät nicht gezeichnet wird."""
|
"""(kind, icon_png_bytes) oder (None, None), wenn das Gerät nicht gezeichnet wird."""
|
||||||
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
|
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
from netbox.plugins import PluginTemplateExtension
|
from netbox.plugins import PluginTemplateExtension
|
||||||
|
|
||||||
|
|
||||||
@@ -13,8 +14,9 @@ class CustomerExportButton(PluginTemplateExtension):
|
|||||||
kwargs={"kind": obj._meta.model_name, "pk": obj.pk},
|
kwargs={"kind": obj._meta.model_name, "pk": obj.pk},
|
||||||
)
|
)
|
||||||
return format_html(
|
return format_html(
|
||||||
'<a href="{}" class="btn btn-primary"><i class="mdi mdi-file-document-outline"></i> Kundendoku</a>',
|
'<a href="{}" class="btn btn-primary"><i class="mdi mdi-file-document-outline"></i> {}</a>',
|
||||||
url,
|
url,
|
||||||
|
_("Customer Docs"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -37,7 +39,7 @@ class TopologySymbolButton(PluginTemplateExtension):
|
|||||||
else:
|
else:
|
||||||
url = f"{reverse('plugins:netbox_customer_export:symbol_add')}?{field}={obj.pk}"
|
url = f"{reverse('plugins:netbox_customer_export:symbol_add')}?{field}={obj.pk}"
|
||||||
return format_html(
|
return format_html(
|
||||||
'<a href="{}" class="btn btn-outline-primary"><i class="mdi mdi-shape-outline"></i> Topologie-Symbol</a>', url
|
'<a href="{}" class="btn btn-outline-primary"><i class="mdi mdi-shape-outline"></i> {}</a>', url, _("Topology Symbol")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div class="ce-pills">
|
{% load i18n %}<div class="ce-pills">
|
||||||
{% for cb in field %}
|
{% for cb in field %}
|
||||||
<input type="checkbox" class="btn-check" name="{{ cb.data.name }}" value="{{ cb.data.value }}" id="{{ cb.id_for_label }}" autocomplete="off"{% if cb.data.selected %} checked{% endif %}>
|
<input type="checkbox" class="btn-check" name="{{ cb.data.name }}" value="{{ cb.data.value }}" id="{{ cb.id_for_label }}" autocomplete="off"{% if cb.data.selected %} checked{% endif %}>
|
||||||
<label class="btn btn-sm btn-outline-primary" for="{{ cb.id_for_label }}">{{ cb.choice_label }}</label>
|
<label class="btn btn-sm btn-outline-primary" for="{{ cb.id_for_label }}">{{ cb.choice_label }}</label>
|
||||||
{% empty %}<span class="text-muted small">Keine Einträge im Scope.</span>{% endfor %}
|
{% empty %}<span class="text-muted small">{% trans "No entries in scope." %}</span>{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<div class="table-responsive">
|
{% load i18n %}<div class="table-responsive">
|
||||||
<table class="table table-hover card-table align-middle">
|
<table class="table table-hover card-table align-middle">
|
||||||
<thead><tr><th style="width:56px"></th><th>Zuordnung</th><th>Symbol</th><th></th></tr></thead>
|
<thead><tr><th style="width:56px"></th><th>{% trans "Assignment" %}</th><th>{% trans "Symbol" %}</th><th></th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for s, preview in rows %}
|
{% for s, preview in rows %}
|
||||||
<tr>
|
<tr>
|
||||||
@@ -9,13 +9,13 @@
|
|||||||
{% if s.device_type %}<a href="{{ s.device_type.get_absolute_url }}">{{ s.device_type.manufacturer }} {{ s.device_type.model }}</a>
|
{% if s.device_type %}<a href="{{ s.device_type.get_absolute_url }}">{{ s.device_type.manufacturer }} {{ s.device_type.model }}</a>
|
||||||
{% else %}<a href="{{ s.role.get_absolute_url }}">{{ s.role }}</a>{% endif %}
|
{% else %}<a href="{{ s.role.get_absolute_url }}">{{ s.role }}</a>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>{% if s.icon %}<span class="badge text-bg-blue">Eigenes Icon</span>{% endif %} {{ s.get_kind_display }}</td>
|
<td>{% if s.icon %}<span class="badge text-bg-blue">{% trans "Custom icon" %}</span>{% endif %} {{ s.get_kind_display }}</td>
|
||||||
<td class="text-end text-nowrap">
|
<td class="text-end text-nowrap">
|
||||||
{% if perms.netbox_customer_export.change_topologysymbol %}
|
{% if perms.netbox_customer_export.change_topologysymbol %}
|
||||||
<a href="{{ s.get_absolute_url }}" class="btn btn-sm btn-warning" title="Bearbeiten"><i class="mdi mdi-pencil"></i></a>
|
<a href="{{ s.get_absolute_url }}" class="btn btn-sm btn-warning" title="{% trans "Edit" %}"><i class="mdi mdi-pencil"></i></a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if perms.netbox_customer_export.delete_topologysymbol %}
|
{% if perms.netbox_customer_export.delete_topologysymbol %}
|
||||||
<a href="{% url 'plugins:netbox_customer_export:symbol_delete' pk=s.pk %}" class="btn btn-sm btn-danger" title="Löschen"><i class="mdi mdi-trash-can-outline"></i></a>
|
<a href="{% url 'plugins:netbox_customer_export:symbol_delete' pk=s.pk %}" class="btn btn-sm btn-danger" title="{% trans "Delete" %}"><i class="mdi mdi-trash-can-outline"></i></a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
{% block title %}{{ object }} löschen{% endblock %}
|
{% load i18n %}
|
||||||
|
{% block title %}{% blocktrans %}Delete {{ object }}{% endblocktrans %}{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<form method="post" class="mt-3">
|
<form method="post" class="mt-3">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div class="card border-danger">
|
<div class="card border-danger">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<p>Soll das Branding-Profil <strong>{{ object }}</strong> wirklich gelöscht werden?
|
<p>{% blocktrans trimmed %}Do you really want to delete the branding profile <strong>{{ object }}</strong>?
|
||||||
Logo und Word-Vorlage des Profils werden ebenfalls entfernt.</p>
|
The profile's logo and Word template will be removed as well.{% endblocktrans %}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-footer text-end">
|
<div class="card-footer text-end">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
|
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
|
||||||
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> Löschen</button>
|
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> {% trans "Delete" %}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
{% block title %}{% if object.pk %}{{ object }} bearbeiten{% else %}Neues Branding-Profil{% endif %}{% endblock %}
|
{% load i18n %}
|
||||||
|
{% block title %}{% if object.pk %}{% blocktrans %}Edit {{ object }}{% endblocktrans %}{% else %}{% trans "New branding profile" %}{% endif %}{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<style>
|
<style>
|
||||||
.ce-colors { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: .75rem; }
|
.ce-colors { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: .75rem; }
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<div class="col-lg-6">
|
<div class="col-lg-6">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
<h2 class="card-header"><i class="mdi mdi-domain"></i> Allgemein</h2>
|
<h2 class="card-header"><i class="mdi mdi-domain"></i> {% trans "General" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
{% include 'netbox_customer_export/_field.html' with field=form.name %}
|
{% include 'netbox_customer_export/_field.html' with field=form.name %}
|
||||||
<div class="mb-3 d-flex gap-2 align-items-center">{{ form.is_default }} <label for="{{ form.is_default.id_for_label }}" class="m-0">{{ form.is_default.label }}</label>
|
<div class="mb-3 d-flex gap-2 align-items-center">{{ form.is_default }} <label for="{{ form.is_default.id_for_label }}" class="m-0">{{ form.is_default.label }}</label>
|
||||||
@@ -23,7 +24,7 @@
|
|||||||
{% include 'netbox_customer_export/_field.html' with field=form.footer_text %}
|
{% include 'netbox_customer_export/_field.html' with field=form.footer_text %}
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label class="form-label" for="{{ form.logo.id_for_label }}">{{ form.logo.label }}</label>
|
<label class="form-label" for="{{ form.logo.id_for_label }}">{{ form.logo.label }}</label>
|
||||||
{% if object.logo %}<div class="mb-2"><img src="{{ object.logo.url }}" class="ce-logo-preview" alt="Aktuelles Logo"></div>{% endif %}
|
{% if object.logo %}<div class="mb-2"><img src="{{ object.logo.url }}" class="ce-logo-preview" alt="{% trans "Current logo" %}"></div>{% endif %}
|
||||||
{{ form.logo }}
|
{{ form.logo }}
|
||||||
<div class="form-text">{{ form.logo.help_text }}</div>
|
<div class="form-text">{{ form.logo.help_text }}</div>
|
||||||
{% for e in form.logo.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
|
{% for e in form.logo.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
|
||||||
@@ -34,7 +35,7 @@
|
|||||||
|
|
||||||
<div class="col-lg-6">
|
<div class="col-lg-6">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
<h2 class="card-header"><i class="mdi mdi-palette"></i> Farben & Schrift</h2>
|
<h2 class="card-header"><i class="mdi mdi-palette"></i> {% trans "Colours & font" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="ce-colors mb-3">
|
<div class="ce-colors mb-3">
|
||||||
{% for field in form %}{% if field.name in 'primary_color accent_color header_text_color label_bg_color stripe_color' %}
|
{% for field in form %}{% if field.name in 'primary_color accent_color header_text_color label_bg_color stripe_color' %}
|
||||||
@@ -73,9 +74,9 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-end gap-2 mt-3">
|
<div class="d-flex justify-content-end gap-2 mt-3">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
|
<a href="{% url 'plugins:netbox_customer_export:branding_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
|
||||||
{% if object.pk %}<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=object.pk %}" target="_blank" class="btn btn-outline-primary"><i class="mdi mdi-eye"></i> Vorschau</a>{% endif %}
|
{% if object.pk %}<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=object.pk %}" target="_blank" class="btn btn-outline-primary"><i class="mdi mdi-eye"></i> {% trans "Preview" %}</a>{% endif %}
|
||||||
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> Speichern</button>
|
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> {% trans "Save" %}</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
{% block title %}Branding-Profile{% endblock %}
|
{% load i18n %}
|
||||||
|
{% block title %}{% trans "Branding Profiles" %}{% endblock %}
|
||||||
{% block controls %}
|
{% block controls %}
|
||||||
{% if perms.netbox_customer_export.add_brandingprofile %}
|
{% if perms.netbox_customer_export.add_brandingprofile %}
|
||||||
<div class="btn-list">
|
<div class="btn-list">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:branding_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> Hinzufügen</a>
|
<a href="{% url 'plugins:netbox_customer_export:branding_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> {% trans "Add" %}</a>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -16,38 +17,38 @@
|
|||||||
<div class="table-responsive">
|
<div class="table-responsive">
|
||||||
<table class="table table-hover card-table">
|
<table class="table table-hover card-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>Name</th><th>Logo</th><th>Firma</th><th>Farben</th><th>Schrift</th><th>Word-Vorlage</th><th></th></tr>
|
<tr><th>{% trans "Name" %}</th><th>{% trans "Logo" %}</th><th>{% trans "Company" %}</th><th>{% trans "Colours" %}</th><th>{% trans "Font" %}</th><th>{% trans "Word template" %}</th><th></th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for p in profiles %}
|
{% for p in profiles %}
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
{% if perms.netbox_customer_export.change_brandingprofile %}<a href="{{ p.get_absolute_url }}">{{ p.name }}</a>{% else %}{{ p.name }}{% endif %}
|
{% if perms.netbox_customer_export.change_brandingprofile %}<a href="{{ p.get_absolute_url }}">{{ p.name }}</a>{% else %}{{ p.name }}{% endif %}
|
||||||
{% if p.is_default %}<span class="badge text-bg-green ms-1">Standard</span>{% endif %}
|
{% if p.is_default %}<span class="badge text-bg-green ms-1">{% trans "Default" %}</span>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>{% if p.logo %}<img src="{{ p.logo.url }}" class="ce-logo" alt="">{% else %}<span class="text-muted">—</span>{% endif %}</td>
|
<td>{% if p.logo %}<img src="{{ p.logo.url }}" class="ce-logo" alt="">{% else %}<span class="text-muted">—</span>{% endif %}</td>
|
||||||
<td>{{ p.company_name|default:"—" }}</td>
|
<td>{{ p.company_name|default:"—" }}</td>
|
||||||
<td>
|
<td>
|
||||||
<span class="ce-swatch" style="background:#{{ p.primary_color }}" title="Primär #{{ p.primary_color }}"></span>
|
<span class="ce-swatch" style="background:#{{ p.primary_color }}" title="{% trans "Primary" %} #{{ p.primary_color }}"></span>
|
||||||
<span class="ce-swatch" style="background:#{{ p.accent_color }}" title="Akzent #{{ p.accent_color }}"></span>
|
<span class="ce-swatch" style="background:#{{ p.accent_color }}" title="{% trans "Accent" %} #{{ p.accent_color }}"></span>
|
||||||
<span class="ce-swatch" style="background:#{{ p.label_bg_color }}" title="Beschriftungen #{{ p.label_bg_color }}"></span>
|
<span class="ce-swatch" style="background:#{{ p.label_bg_color }}" title="{% trans "Labels" %} #{{ p.label_bg_color }}"></span>
|
||||||
<span class="ce-swatch" style="background:#{{ p.stripe_color }}" title="Zebrastreifen #{{ p.stripe_color }}"></span>
|
<span class="ce-swatch" style="background:#{{ p.stripe_color }}" title="{% trans "Row stripes" %} #{{ p.stripe_color }}"></span>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ p.font_family }}, {{ p.font_size }} pt</td>
|
<td>{{ p.font_family }}, {{ p.font_size }} pt</td>
|
||||||
<td>{% if p.docx_template %}<i class="mdi mdi-file-word-box text-primary"></i> {{ p.docx_template.name|cut:"customer-export/templates/" }}{% else %}<span class="text-muted">—</span>{% endif %}</td>
|
<td>{% if p.docx_template %}<i class="mdi mdi-file-word-box text-primary"></i> {{ p.docx_template.name|cut:"customer-export/templates/" }}{% else %}<span class="text-muted">—</span>{% endif %}</td>
|
||||||
<td class="text-end text-nowrap">
|
<td class="text-end text-nowrap">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=p.pk %}" target="_blank" class="btn btn-sm btn-outline-secondary" title="Vorschau"><i class="mdi mdi-eye"></i></a>
|
<a href="{% url 'plugins:netbox_customer_export:branding_preview' pk=p.pk %}" target="_blank" class="btn btn-sm btn-outline-secondary" title="{% trans "Preview" %}"><i class="mdi mdi-eye"></i></a>
|
||||||
{% if perms.netbox_customer_export.change_brandingprofile %}
|
{% if perms.netbox_customer_export.change_brandingprofile %}
|
||||||
<a href="{{ p.get_absolute_url }}" class="btn btn-sm btn-warning" title="Bearbeiten"><i class="mdi mdi-pencil"></i></a>
|
<a href="{{ p.get_absolute_url }}" class="btn btn-sm btn-warning" title="{% trans "Edit" %}"><i class="mdi mdi-pencil"></i></a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if perms.netbox_customer_export.delete_brandingprofile %}
|
{% if perms.netbox_customer_export.delete_brandingprofile %}
|
||||||
<a href="{% url 'plugins:netbox_customer_export:branding_delete' pk=p.pk %}" class="btn btn-sm btn-danger" title="Löschen"><i class="mdi mdi-trash-can-outline"></i></a>
|
<a href="{% url 'plugins:netbox_customer_export:branding_delete' pk=p.pk %}" class="btn btn-sm btn-danger" title="{% trans "Delete" %}"><i class="mdi mdi-trash-can-outline"></i></a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% empty %}
|
{% empty %}
|
||||||
<tr><td colspan="7" class="text-center text-muted py-4">
|
<tr><td colspan="7" class="text-center text-muted py-4">
|
||||||
Noch keine Branding-Profile angelegt. Bis dahin gelten die Einstellungen aus <code>configuration.py</code>.
|
{% blocktrans trimmed %}No branding profiles yet. Until then, the settings from <code>configuration.py</code> apply.{% endblocktrans %}
|
||||||
</td></tr>
|
</td></tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<!DOCTYPE html>
|
{% load i18n %}<!DOCTYPE html>
|
||||||
<html lang="de">
|
{% get_current_language as LANGUAGE_CODE %}<html lang="{{ LANGUAGE_CODE }}">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<title>{{ doc.title }}</title>
|
<title>{{ doc.title }}</title>
|
||||||
@@ -7,7 +7,9 @@
|
|||||||
:root { --primary: #{{ b.primary_color }}; --accent: #{{ b.accent_color }}; --head-text: #{{ b.header_text_color }}; --label-bg: #{{ b.label_bg_color }}; --stripe: #{{ b.stripe_color }}; }
|
:root { --primary: #{{ b.primary_color }}; --accent: #{{ b.accent_color }}; --head-text: #{{ b.header_text_color }}; --label-bg: #{{ b.label_bg_color }}; --stripe: #{{ b.stripe_color }}; }
|
||||||
@page { size: A4; margin: 20mm 15mm 20mm 15mm;
|
@page { size: A4; margin: 20mm 15mm 20mm 15mm;
|
||||||
@bottom-left { content: element(footer); }
|
@bottom-left { content: element(footer); }
|
||||||
@bottom-right { content: "Seite " counter(page) " / " counter(pages); font-size: 7pt; color: #777; } }
|
@bottom-right { content: "{% filter escapejs %}{% trans "Page" %}{% endfilter %} " counter(page) " / " counter(pages); font-size: 7pt; color: #777; } }
|
||||||
|
/* Landscape: narrow margins so the topology gets as large as possible */
|
||||||
|
@page landscape { size: A4 landscape; margin: 7mm 7mm 11mm 7mm; }
|
||||||
@page cover { @bottom-left { content: none } @bottom-right { content: none } }
|
@page cover { @bottom-left { content: none } @bottom-right { content: none } }
|
||||||
body { font-family: "{{ b.font_family }}", "Segoe UI", "DejaVu Sans", Arial, sans-serif; font-size: {{ b.font_size }}pt; color: #222; }
|
body { font-family: "{{ b.font_family }}", "Segoe UI", "DejaVu Sans", Arial, sans-serif; font-size: {{ b.font_size }}pt; color: #222; }
|
||||||
.cover { page: cover; padding-top: 60mm; page-break-after: always; }
|
.cover { page: cover; padding-top: 60mm; page-break-after: always; }
|
||||||
@@ -27,6 +29,7 @@
|
|||||||
table { width: 100%; border-collapse: collapse; margin: 4pt 0 10pt; font-size: 8.5pt; }
|
table { width: 100%; border-collapse: collapse; margin: 4pt 0 10pt; font-size: 8.5pt; }
|
||||||
thead { display: table-header-group; }
|
thead { display: table-header-group; }
|
||||||
th { background: var(--primary); color: var(--head-text); text-align: left; padding: 3pt 5pt; }
|
th { background: var(--primary); color: var(--head-text); text-align: left; padding: 3pt 5pt; }
|
||||||
|
th, td { overflow-wrap: anywhere; }
|
||||||
td { border-bottom: 1px solid #ddd; padding: 3pt 5pt; vertical-align: top; }
|
td { border-bottom: 1px solid #ddd; padding: 3pt 5pt; vertical-align: top; }
|
||||||
tr { page-break-inside: avoid; }
|
tr { page-break-inside: avoid; }
|
||||||
tbody tr:nth-child(even) td { background: var(--stripe); }
|
tbody tr:nth-child(even) td { background: var(--stripe); }
|
||||||
@@ -35,10 +38,22 @@
|
|||||||
.images { display: flex; gap: 12mm; justify-content: center; page-break-inside: avoid; }
|
.images { display: flex; gap: 12mm; justify-content: center; page-break-inside: avoid; }
|
||||||
.images figure { margin: 0; text-align: center; }
|
.images figure { margin: 0; text-align: center; }
|
||||||
.images img { max-height: 190mm; max-width: 80mm; }
|
.images img { max-height: 190mm; max-width: 80mm; }
|
||||||
.images.wide img { max-width: 100%; max-height: 240mm; }
|
.images.wide figure { width: 100%; min-width: 0; }
|
||||||
|
.images.wide img { width: 100%; height: auto; max-height: 240mm; object-fit: contain; }
|
||||||
|
.images.photos { display: flex; gap: 6mm; justify-content: flex-start; page-break-inside: avoid; }
|
||||||
|
.images.photos figure { width: calc(50% - 3mm); margin: 0 0 6mm; }
|
||||||
|
.images.photos img { width: 100%; height: auto; max-width: none; max-height: 95mm; object-fit: contain; border: 1px solid #ddd; }
|
||||||
|
.ref { font-size: 8.5pt; color: #555; margin: 2pt 0 8pt; }
|
||||||
|
.ref a { color: var(--primary); text-decoration: none; border-bottom: 1px solid currentColor; }
|
||||||
figcaption { font-style: italic; color: #555; }
|
figcaption { font-style: italic; color: #555; }
|
||||||
.footer { position: running(footer); font-size: 7pt; color: #777; }
|
.footer { position: running(footer); font-size: 7pt; color: #777; }
|
||||||
@media screen { .footer { display: none; } }
|
@media screen { .footer { display: none; } }
|
||||||
|
.landscape { page: landscape; page-break-before: always; page-break-after: always; }
|
||||||
|
.landscape h1 { page-break-before: avoid; margin: 0 0 2pt 0; font-size: 15pt; padding-bottom: 1pt; }
|
||||||
|
.landscape h2 { margin: 2pt 0 3pt 0; font-size: 12pt; }
|
||||||
|
.landscape h3 { margin: 2pt 0 3pt 0; font-size: 11pt; }
|
||||||
|
.landscape img { display: block; margin: 0 auto; max-width: 100%; max-height: 172mm; }
|
||||||
|
@media screen { .landscape img { max-height: none; width: 100%; } }
|
||||||
.pagebreak { page-break-after: always; }
|
.pagebreak { page-break-after: always; }
|
||||||
@media screen { body { max-width: 1100px; margin: auto; padding: 16px; } }
|
@media screen { body { max-width: 1100px; margin: auto; padding: 16px; } }
|
||||||
{{ b.extra_css|safe }}
|
{{ b.extra_css|safe }}
|
||||||
@@ -51,27 +66,33 @@
|
|||||||
<h1>{{ doc.title }}</h1>
|
<h1>{{ doc.title }}</h1>
|
||||||
{% if doc.subtitle %}<div class="subtitle">{{ doc.subtitle }}</div>{% endif %}
|
{% if doc.subtitle %}<div class="subtitle">{{ doc.subtitle }}</div>{% endif %}
|
||||||
<div class="meta">
|
<div class="meta">
|
||||||
Stand: {{ doc.meta.date }}<br>
|
{% trans "As of" %}: {{ doc.meta.date }}<br>
|
||||||
Erstellt von: {{ doc.meta.author }}<br>
|
{% trans "Created by" %}: {{ doc.meta.author }}<br>
|
||||||
{{ b.company_name }}
|
{{ b.company_name }}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<nav class="toc">
|
<nav class="toc">
|
||||||
<h2>Inhaltsverzeichnis</h2>
|
<h2>{% trans "Table of contents" %}</h2>
|
||||||
{% for h in doc.toc %}<div class="l{{ h.level }}"><a href="#{{ h.anchor }}">{{ h.text }}</a></div>{% endfor %}
|
{% for h in doc.toc %}<div class="l{{ h.level }}"><a href="#{{ h.anchor }}">{{ h.text }}</a></div>{% endfor %}
|
||||||
</nav>
|
</nav>
|
||||||
{% for b in doc.blocks %}
|
{% for b in doc.blocks %}
|
||||||
{% if b.kind == 'heading' %}
|
{% if b.kind == 'heading' %}
|
||||||
{% if b.level == 1 %}<h1 id="{{ b.anchor }}">{{ b.text }}</h1>{% elif b.level == 2 %}<h2 id="{{ b.anchor }}">{{ b.text }}</h2>{% elif b.level == 3 %}<h3 id="{{ b.anchor }}">{{ b.text }}</h3>{% else %}<h4 id="{{ b.anchor }}">{{ b.text }}</h4>{% endif %}
|
{% if b.level == 1 %}<h1 id="{{ b.anchor }}">{{ b.text }}</h1>{% elif b.level == 2 %}<h2 id="{{ b.anchor }}">{{ b.text }}</h2>{% elif b.level == 3 %}<h3 id="{{ b.anchor }}">{{ b.text }}</h3>{% else %}<h4 id="{{ b.anchor }}">{{ b.text }}</h4>{% endif %}
|
||||||
{% elif b.kind == 'paragraph' %}<p>{{ b.text|linebreaksbr }}</p>
|
{% elif b.kind == 'paragraph' %}<p>{{ b.text|linebreaksbr }}</p>
|
||||||
|
{% elif b.kind == 'ref' %}<p class="ref">{{ b.rows.0 }}<a href="#{{ b.anchor }}">{{ b.text }}</a></p>
|
||||||
{% elif b.kind == 'table' %}
|
{% elif b.kind == 'table' %}
|
||||||
<table><thead><tr>{% for h in b.headers %}<th>{{ h }}</th>{% endfor %}</tr></thead>
|
<table><thead><tr>{% for h in b.headers %}<th>{{ h }}</th>{% endfor %}</tr></thead>
|
||||||
<tbody>{% for row in b.rows %}<tr>{% for c in row %}<td>{{ c }}</td>{% endfor %}</tr>{% endfor %}</tbody></table>
|
<tbody>{% for row in b.rows %}<tr>{% for c in row %}<td>{{ c|linebreaksbr }}</td>{% endfor %}</tr>{% endfor %}</tbody></table>
|
||||||
{% elif b.kind == 'kv' %}
|
{% elif b.kind == 'kv' %}
|
||||||
<table class="kv"><tbody>{% for row in b.rows %}<tr><td>{{ row.0 }}</td><td>{{ row.1|linebreaksbr }}</td></tr>{% endfor %}</tbody></table>
|
<table class="kv"><tbody>{% for row in b.rows %}<tr><td>{{ row.0 }}</td><td>{{ row.1|linebreaksbr }}</td></tr>{% endfor %}</tbody></table>
|
||||||
{% elif b.kind == 'images' %}
|
{% elif b.kind == 'images' %}
|
||||||
<div class="images{% if b.level == 1 %} wide{% endif %}">{% for img in b.images %}<figure><img src="{{ img.data_uri }}" alt="{{ img.caption }}">{% if img.caption %}<figcaption>{{ img.caption }}</figcaption>{% endif %}</figure>{% endfor %}</div>
|
<div class="images{% if b.level == 1 %} wide{% elif b.level == 2 %} photos{% endif %}">{% for img in b.images %}<figure><img src="{{ img.data_uri }}" alt="{{ img.caption }}">{% if img.caption %}<figcaption>{{ img.caption }}</figcaption>{% endif %}</figure>{% endfor %}</div>
|
||||||
{% elif b.kind == 'pagebreak' %}<div class="pagebreak"></div>
|
{% elif b.kind == 'pagebreak' %}<div class="pagebreak"></div>
|
||||||
|
{% elif b.kind == 'landscape' %}
|
||||||
|
<section class="landscape">
|
||||||
|
{% for h in b.rows %}{% if h.level == 1 %}<h1 id="{{ h.anchor }}">{{ h.text }}</h1>{% elif h.level == 2 %}<h2 id="{{ h.anchor }}">{{ h.text }}</h2>{% else %}<h3 id="{{ h.anchor }}">{{ h.text }}</h3>{% endif %}{% endfor %}
|
||||||
|
<img src="{{ b.images.0.data_uri }}" alt="">
|
||||||
|
</section>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
|
{% load i18n %}
|
||||||
{% load form_helpers %}
|
{% load form_helpers %}
|
||||||
{% block title %}Kundendokumentation: {{ object }}{% endblock %}
|
{% block title %}{% blocktrans %}Customer documentation: {{ object }}{% endblocktrans %}{% endblock %}
|
||||||
{% block subtitle %}
|
{% block subtitle %}
|
||||||
<div class="text-muted"><span class="badge text-bg-secondary">{{ scope.label }}</span> <a href="{{ object.get_absolute_url }}">{{ object }}</a></div>
|
<div class="text-muted"><span class="badge text-bg-secondary">{{ scope.label }}</span> <a href="{{ object.get_absolute_url }}">{{ object }}</a></div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -25,6 +26,13 @@
|
|||||||
.ce-card { transition: opacity .15s; }
|
.ce-card { transition: opacity .15s; }
|
||||||
.ce-actions { position: sticky; bottom: 0; z-index: 10; background: var(--tblr-bg-surface); border-top: 1px solid var(--tblr-border-color); padding: .75rem 1rem; display: flex; justify-content: flex-end; gap: .5rem; }
|
.ce-actions { position: sticky; bottom: 0; z-index: 10; background: var(--tblr-bg-surface); border-top: 1px solid var(--tblr-border-color); padding: .75rem 1rem; display: flex; justify-content: flex-end; gap: .5rem; }
|
||||||
.ce-format .btn { flex: 1; padding-left: .25rem; padding-right: .25rem; }
|
.ce-format .btn { flex: 1; padding-left: .25rem; padding-right: .25rem; }
|
||||||
|
.ce-photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: .5rem; }
|
||||||
|
.ce-photo { position: relative; margin: 0; border: 1px solid var(--tblr-border-color); border-radius: .375rem; overflow: hidden; cursor: pointer; background: var(--tblr-bg-surface-secondary); }
|
||||||
|
.ce-photo:has(input:checked) { border-color: var(--tblr-primary); box-shadow: 0 0 0 1px var(--tblr-primary); }
|
||||||
|
.ce-photo img { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; }
|
||||||
|
.ce-photo .form-check-input { position: absolute; top: .4rem; left: .4rem; margin: 0; }
|
||||||
|
.ce-photo span { display: block; padding: .25rem .4rem; font-size: .75rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.ce-photo-rack + .ce-photo-rack { margin-top: .9rem; }
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<form method="post" class="mt-3" id="ce-export-form">
|
<form method="post" class="mt-3" id="ce-export-form">
|
||||||
@@ -35,29 +43,32 @@
|
|||||||
{# --- links: Dokument --- #}
|
{# --- links: Dokument --- #}
|
||||||
<div class="col-xl-4">
|
<div class="col-xl-4">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="card-header"><i class="mdi mdi-file-document-outline"></i> Dokument</h2>
|
<h2 class="card-header"><i class="mdi mdi-file-document-outline"></i> {% trans "Document" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="ce-label mt-0">Format</div>
|
<div class="ce-label mt-0">{% trans "Format" %}</div>
|
||||||
<div class="btn-group w-100 ce-format mb-3" role="group">
|
<div class="btn-group w-100 ce-format mb-3" role="group">
|
||||||
{% for value, label in form.format.field.choices %}
|
{% for value, label in form.format.field.choices %}
|
||||||
<input type="radio" class="btn-check" name="format" id="fmt-{{ value }}" value="{{ value }}" autocomplete="off"{% if form.format.value == value %} checked{% endif %}>
|
<input type="radio" class="btn-check" name="format" id="fmt-{{ value }}" value="{{ value }}" autocomplete="off"{% if form.format.value == value %} checked{% endif %}>
|
||||||
<label class="btn btn-outline-primary" for="fmt-{{ value }}">
|
<label class="btn btn-outline-primary" for="fmt-{{ value }}">
|
||||||
{% if value == 'pdf' %}<i class="mdi mdi-file-pdf-box"></i>{% elif value == 'docx' %}<i class="mdi mdi-file-word-box"></i>{% elif value == 'drawio' %}<i class="mdi mdi-sitemap"></i>{% else %}<i class="mdi mdi-web"></i>{% endif %}
|
{% if value == 'pdf' %}<i class="mdi mdi-file-pdf-box"></i>{% elif value == 'docx' %}<i class="mdi mdi-file-word-box"></i>{% else %}<i class="mdi mdi-web"></i>{% endif %}
|
||||||
{{ label }}
|
{{ label }}
|
||||||
</label>
|
</label>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
<div class="form-text mt-n2 mb-3" id="ce-drawio-hint" hidden>draw.io exportiert nur die Topologie als bearbeitbares Diagramm (Optionen unten bei „Topologie“).</div>
|
<div class="mb-3"><label class="form-label" for="{{ form.title.id_for_label }}">{{ form.title.label }}</label>{{ form.title }}</div>
|
||||||
<div class="mb-3"><label class="form-label" for="{{ form.title.id_for_label }}">Titel</label>{{ form.title }}</div>
|
<div class="mb-3"><label class="form-label" for="{{ form.subtitle.id_for_label }}">{{ form.subtitle.label }}</label>{{ form.subtitle }}</div>
|
||||||
<div class="mb-3"><label class="form-label" for="{{ form.subtitle.id_for_label }}">Untertitel</label>{{ form.subtitle }}</div>
|
<div class="mb-3"><label class="form-label" for="{{ form.author.id_for_label }}">{{ form.author.label }}</label>{{ form.author }}<div class="form-text">{% trans "Empty = your user name" %}</div></div>
|
||||||
<div class="mb-3"><label class="form-label" for="{{ form.author.id_for_label }}">Erstellt von</label>{{ form.author }}<div class="form-text">Leer = dein Benutzername</div></div>
|
|
||||||
{% if form.branding.field.choices|length > 1 %}
|
{% if form.branding.field.choices|length > 1 %}
|
||||||
<div class="mb-3"><label class="form-label" for="{{ form.branding.id_for_label }}">Design / Firma</label>{{ form.branding }}</div>
|
<div class="mb-3"><label class="form-label" for="{{ form.branding.id_for_label }}">{{ form.branding.label }}</label>{{ form.branding }}</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<input type="hidden" name="branding" value="{{ form.branding.field.choices.0.0 }}">
|
<input type="hidden" name="branding" value="{{ form.branding.field.choices.0.0 }}">
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<div class="ce-label">Optionen</div>
|
<div class="ce-label">{{ form.ip_versions.label }}</div>
|
||||||
|
{% include 'netbox_customer_export/_pills.html' with field=form.ip_versions %}
|
||||||
|
<div class="form-text mb-2">{% trans "Applies to management/OOB IPs, VMs, topology, IP networks and IP addresses." %}</div>
|
||||||
|
|
||||||
|
<div class="ce-label">{% trans "Options" %}</div>
|
||||||
<label class="ce-switch">{{ form.include_empty }} {{ form.include_empty.label }}</label>
|
<label class="ce-switch">{{ form.include_empty }} {{ form.include_empty.label }}</label>
|
||||||
{% if form.include_secrets %}
|
{% if form.include_secrets %}
|
||||||
<label class="ce-switch text-danger">{{ form.include_secrets }} {{ form.include_secrets.label }}</label>
|
<label class="ce-switch text-danger">{{ form.include_secrets }} {{ form.include_secrets.label }}</label>
|
||||||
@@ -69,13 +80,13 @@
|
|||||||
{# --- rechts: Inhalte + Detailoptionen --- #}
|
{# --- rechts: Inhalte + Detailoptionen --- #}
|
||||||
<div class="col-xl-8">
|
<div class="col-xl-8">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="card-header"><i class="mdi mdi-format-list-checks"></i> Inhalte</h2>
|
<h2 class="card-header"><i class="mdi mdi-format-list-checks"></i> {% trans "Contents" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
{% for group, sections in section_groups.items %}
|
{% for group, sections in section_groups.items %}
|
||||||
<div class="ce-group" data-ce-group>
|
<div class="ce-group" data-ce-group>
|
||||||
<div class="ce-group-head">
|
<div class="ce-group-head">
|
||||||
<h5>{{ group }}</h5>
|
<h5>{{ group }}</h5>
|
||||||
<span><a data-ce-all>Alle</a> · <a data-ce-none>Keine</a></span>
|
<span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="ce-tiles">
|
<div class="ce-tiles">
|
||||||
{% for cb in form.sections %}{% for s in sections %}{% if s.key == cb.data.value %}
|
{% for cb in form.sections %}{% for s in sections %}{% if s.key == cb.data.value %}
|
||||||
@@ -93,13 +104,13 @@
|
|||||||
<div class="row g-3 mt-0">
|
<div class="row g-3 mt-0">
|
||||||
<div class="col-lg-7">
|
<div class="col-lg-7">
|
||||||
<div class="card ce-card h-100" data-ce-depends="devices">
|
<div class="card ce-card h-100" data-ce-depends="devices">
|
||||||
<h2 class="card-header"><i class="mdi mdi-server-network"></i> Geräte</h2>
|
<h2 class="card-header"><i class="mdi mdi-server-network"></i> {% trans "Devices" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div data-ce-group>
|
<div data-ce-group>
|
||||||
<div class="ce-group-head"><h5>Geräterollen</h5><span><a data-ce-all>Alle</a> · <a data-ce-none>Keine</a></span></div>
|
<div class="ce-group-head"><h5>{{ form.roles.label }}</h5><span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span></div>
|
||||||
{% include 'netbox_customer_export/_pills.html' with field=form.roles %}
|
{% include 'netbox_customer_export/_pills.html' with field=form.roles %}
|
||||||
</div>
|
</div>
|
||||||
<div class="ce-label">Spalten</div>
|
<div class="ce-label">{% trans "Columns" %}</div>
|
||||||
{% include 'netbox_customer_export/_pills.html' with field=form.device_columns %}
|
{% include 'netbox_customer_export/_pills.html' with field=form.device_columns %}
|
||||||
<label class="ce-switch mt-3">{{ form.group_by_site }} {{ form.group_by_site.label }}</label>
|
<label class="ce-switch mt-3">{{ form.group_by_site }} {{ form.group_by_site.label }}</label>
|
||||||
</div>
|
</div>
|
||||||
@@ -107,30 +118,68 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="col-lg-5">
|
<div class="col-lg-5">
|
||||||
<div class="card ce-card h-100" data-ce-depends="racks">
|
<div class="card ce-card h-100" data-ce-depends="racks">
|
||||||
<h2 class="card-header"><i class="mdi mdi-server"></i> Racks</h2>
|
<h2 class="card-header"><i class="mdi mdi-server"></i> {% trans "Racks" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<label class="ce-switch">{{ form.rack_svg }} Rack-Ansichten einbetten</label>
|
<label class="ce-switch">{{ form.rack_svg }} {% trans "Embed rack elevations" %}</label>
|
||||||
<label class="ce-switch">{{ form.rack_images }} {{ form.rack_images.label }}</label>
|
<label class="ce-switch">{{ form.rack_images }} {{ form.rack_images.label }}</label>
|
||||||
<div class="ce-label">Seiten</div>
|
<div class="ce-label">{% trans "Faces" %}</div>
|
||||||
{% include 'netbox_customer_export/_pills.html' with field=form.rack_faces %}
|
{% include 'netbox_customer_export/_pills.html' with field=form.rack_faces %}
|
||||||
<div class="ce-label">Weiteres</div>
|
<div class="ce-label">{% trans "More" %}</div>
|
||||||
<label class="ce-switch">{{ form.rack_devices }} {{ form.rack_devices.label }}</label>
|
<label class="ce-switch">{{ form.rack_devices }} {{ form.rack_devices.label }}</label>
|
||||||
<label class="ce-switch">{{ form.rack_pagebreak }} {{ form.rack_pagebreak.label }}</label>
|
<label class="ce-switch">{{ form.rack_pagebreak }} {{ form.rack_pagebreak.label }}</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="col-lg-5">
|
||||||
|
<div class="card ce-card h-100" data-ce-depends="disks">
|
||||||
|
<h2 class="card-header"><i class="mdi mdi-harddisk"></i> {% trans "Disks" %}</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
<label class="ce-switch">{{ form.disk_install_date }} {{ form.disk_install_date.label }}</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card ce-card mt-3" data-ce-depends="racks">
|
||||||
|
<h2 class="card-header"><i class="mdi mdi-image-multiple-outline"></i> {% trans "Rack photos" %}</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
{% if not rack_photos %}
|
||||||
|
<div class="text-secondary">{% trans "No image attachments found on racks in this scope. Photos can be uploaded on the rack via <em>Attach an image</em>." %}</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="form-text mt-0 mb-3">{% trans "Selected photos appear in the appendix at the end of the document; a link to them is placed below the rack elevation." %}</div>
|
||||||
|
{% for rack, atts in rack_photos %}
|
||||||
|
<div class="ce-photo-rack" data-ce-group>
|
||||||
|
<div class="ce-group-head">
|
||||||
|
<h5>{{ rack.name }} <span class="fw-normal" style="text-transform: none">· {{ rack.site }}{% if rack.location %} / {{ rack.location }}{% endif %}</span></h5>
|
||||||
|
<span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span>
|
||||||
|
</div>
|
||||||
|
<div class="ce-photos">
|
||||||
|
{% for a in atts %}
|
||||||
|
<label class="ce-photo" title="{{ a.name|default:a.image.name }}">
|
||||||
|
<input type="checkbox" class="form-check-input" name="rack_photos" value="{{ a.pk }}"{% if a.pk|stringformat:"s" in form.rack_photos.value %} checked{% endif %}>
|
||||||
|
<img src="{{ a.image.url }}" alt="" loading="lazy">
|
||||||
|
<span>{{ a.name|default:a.image.name }}</span>
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="card ce-card mt-3" data-ce-depends="topology">
|
<div class="card ce-card mt-3" data-ce-depends="topology">
|
||||||
<h2 class="card-header d-flex justify-content-between align-items-center">
|
<h2 class="card-header d-flex justify-content-between align-items-center">
|
||||||
<span><i class="mdi mdi-sitemap"></i> Topologie</span>
|
<span><i class="mdi mdi-sitemap"></i> {% trans "Topology" %}</span>
|
||||||
{% if perms.netbox_customer_export.view_topologysymbol %}
|
{% if perms.netbox_customer_export.view_topologysymbol %}
|
||||||
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-sm btn-outline-secondary" target="_blank"><i class="mdi mdi-shape-outline"></i> Symbole verwalten</a>
|
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-sm btn-outline-secondary" target="_blank"><i class="mdi mdi-shape-outline"></i> {% trans "Manage symbols" %}</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</h2>
|
</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="ce-label mt-0">Beschriftung</div>
|
<div class="ce-label mt-0">{{ form.topo_scope.label }}</div>
|
||||||
|
{% include 'netbox_customer_export/_pills.html' with field=form.topo_scope %}
|
||||||
|
<div class="form-text mb-2">{% trans "“Location overview” shows all locations of a site and the cables between them, from the server room to the last sub-distribution. “Cross-site” combines all sites in one diagram to show how buildings and their locations are connected. “Per rack” shows each rack separately. Connected devices outside appear dashed." %}</div>
|
||||||
|
<div class="ce-label">{{ form.topo_details.label }}</div>
|
||||||
{% include 'netbox_customer_export/_pills.html' with field=form.topo_details %}
|
{% include 'netbox_customer_export/_pills.html' with field=form.topo_details %}
|
||||||
<div class="ce-label">Weiteres</div>
|
<div class="ce-label">{% trans "More" %}</div>
|
||||||
<label class="ce-switch">{{ form.topo_external }} {{ form.topo_external.label }}</label>
|
<label class="ce-switch">{{ form.topo_external }} {{ form.topo_external.label }}</label>
|
||||||
<label class="ce-switch">{{ form.topo_isolated }} {{ form.topo_isolated.label }}</label>
|
<label class="ce-switch">{{ form.topo_isolated }} {{ form.topo_isolated.label }}</label>
|
||||||
</div>
|
</div>
|
||||||
@@ -139,8 +188,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="ce-actions mt-3">
|
<div class="ce-actions mt-3">
|
||||||
<a href="{{ object.get_absolute_url }}" class="btn btn-outline-secondary">Abbrechen</a>
|
<a href="{{ object.get_absolute_url }}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
|
||||||
<button class="btn btn-primary"><i class="mdi mdi-download"></i> Dokument erstellen</button>
|
<button class="btn btn-primary"><i class="mdi mdi-download"></i> {% trans "Create document" %}</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -156,15 +205,10 @@
|
|||||||
});
|
});
|
||||||
// Detailkarten ausgrauen, wenn der zugehörige Abschnitt abgewählt ist
|
// Detailkarten ausgrauen, wenn der zugehörige Abschnitt abgewählt ist
|
||||||
function sync() {
|
function sync() {
|
||||||
var fmt = document.querySelector('input[name=format]:checked');
|
|
||||||
var drawio = fmt && fmt.value === 'drawio';
|
|
||||||
document.querySelectorAll('[data-ce-depends]').forEach(function (card) {
|
document.querySelectorAll('[data-ce-depends]').forEach(function (card) {
|
||||||
var cb = document.querySelector('input[name=sections][value="' + card.dataset.ceDepends + '"]');
|
var cb = document.querySelector('input[name=sections][value="' + card.dataset.ceDepends + '"]');
|
||||||
// draw.io nutzt nur die Topologie-Optionen
|
card.classList.toggle('ce-dim', !!cb && !cb.checked);
|
||||||
var active = drawio ? card.dataset.ceDepends === 'topology' : (!cb || cb.checked);
|
|
||||||
card.classList.toggle('ce-dim', !active);
|
|
||||||
});
|
});
|
||||||
document.getElementById('ce-drawio-hint').hidden = !drawio;
|
|
||||||
}
|
}
|
||||||
document.addEventListener('change', sync);
|
document.addEventListener('change', sync);
|
||||||
sync();
|
sync();
|
||||||
|
|||||||
@@ -1,20 +1,21 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
|
{% load i18n %}
|
||||||
{% load form_helpers %}
|
{% load form_helpers %}
|
||||||
{% block title %}Kundendokumentation{% endblock %}
|
{% block title %}{% trans "Customer Documentation" %}{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<form method="post" class="container-fluid my-3">
|
<form method="post" class="container-fluid my-3">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="card-header">Scope wählen</h2>
|
<h2 class="card-header">{% trans "Select scope" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<p class="text-muted">Genau eines der Felder ausfüllen.</p>
|
<p class="text-muted">{% trans "Fill in exactly one of the fields." %}</p>
|
||||||
{% if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{% endif %}
|
{% if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{% endif %}
|
||||||
{% render_field form.site %}
|
{% render_field form.site %}
|
||||||
{% render_field form.location %}
|
{% render_field form.location %}
|
||||||
{% render_field form.tenant %}
|
{% render_field form.tenant %}
|
||||||
{% render_field form.tenantgroup %}
|
{% render_field form.tenantgroup %}
|
||||||
</div>
|
</div>
|
||||||
<div class="card-footer text-end"><button class="btn btn-primary">Weiter</button></div>
|
<div class="card-footer text-end"><button class="btn btn-primary">{% trans "Continue" %}</button></div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
{% block title %}Symbol-Zuordnung löschen{% endblock %}
|
{% load i18n %}
|
||||||
|
{% block title %}{% trans "Delete symbol assignment" %}{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<form method="post" class="mt-3">
|
<form method="post" class="mt-3">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div class="card border-danger">
|
<div class="card border-danger">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<p>Soll die Symbol-Zuordnung für <strong>{{ object.target_label }} {{ object }}</strong> gelöscht werden?
|
<p>{% blocktrans trimmed with label=object.target_label %}Delete the symbol assignment for <strong>{{ label }} {{ object }}</strong>?
|
||||||
Danach gilt wieder die automatische Erkennung. Ein hochgeladenes Icon wird ebenfalls entfernt.</p>
|
Automatic detection applies again afterwards. An uploaded icon will be removed as well.{% endblocktrans %}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-footer text-end">
|
<div class="card-footer text-end">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
|
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
|
||||||
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> Löschen</button>
|
<button class="btn btn-danger"><i class="mdi mdi-trash-can-outline"></i> {% trans "Delete" %}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
|
{% load i18n %}
|
||||||
{% load form_helpers %}
|
{% load form_helpers %}
|
||||||
{% block title %}{% if object.pk %}Symbol für {{ object }}{% else %}Neue Symbol-Zuordnung{% endif %}{% endblock %}
|
{% block title %}{% if object.pk %}{% blocktrans %}Symbol for {{ object }}{% endblocktrans %}{% else %}{% trans "New symbol assignment" %}{% endif %}{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<style>
|
<style>
|
||||||
.ce-kinds { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: .5rem; }
|
.ce-kinds { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: .5rem; }
|
||||||
@@ -19,9 +20,9 @@
|
|||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<div class="col-lg-4">
|
<div class="col-lg-4">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
<h2 class="card-header"><i class="mdi mdi-link-variant"></i> Gilt für</h2>
|
<h2 class="card-header"><i class="mdi mdi-link-variant"></i> {% trans "Applies to" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<p class="text-muted small">Entweder einen Gerätetyp <em>oder</em> eine Geräterolle wählen. Gerätetyp hat Vorrang.</p>
|
<p class="text-muted small">{% blocktrans trimmed %}Select either a device type <em>or</em> a device role. The device type takes precedence.{% endblocktrans %}</p>
|
||||||
{% render_field form.device_type %}
|
{% render_field form.device_type %}
|
||||||
{% render_field form.role %}
|
{% render_field form.role %}
|
||||||
</div>
|
</div>
|
||||||
@@ -29,7 +30,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="col-lg-8">
|
<div class="col-lg-8">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> Symbol</h2>
|
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> {% trans "Symbol" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="ce-kinds mb-3">
|
<div class="ce-kinds mb-3">
|
||||||
{% for radio in form.kind %}
|
{% for radio in form.kind %}
|
||||||
@@ -44,12 +45,12 @@
|
|||||||
</div>
|
</div>
|
||||||
{% for e in form.kind.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
|
{% for e in form.kind.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
|
||||||
|
|
||||||
<label class="form-label" for="{{ form.icon.id_for_label }}">Eigenes Icon (optional)</label>
|
<label class="form-label" for="{{ form.icon.id_for_label }}">{% trans "Custom icon (optional)" %}</label>
|
||||||
<div class="d-flex gap-3 align-items-start">
|
<div class="d-flex gap-3 align-items-start">
|
||||||
{% if object.icon %}<img src="{{ object.icon.url }}" class="ce-icon-preview" alt="Aktuelles Icon">{% endif %}
|
{% if object.icon %}<img src="{{ object.icon.url }}" class="ce-icon-preview" alt="{% trans "Current icon" %}">{% endif %}
|
||||||
<div class="flex-grow-1">
|
<div class="flex-grow-1">
|
||||||
{{ form.icon }}
|
{{ form.icon }}
|
||||||
<div class="form-text">{{ form.icon.help_text }} Ist kein Symbol gewählt, bestimmt die Automatik die Ebene im Diagramm.</div>
|
<div class="form-text">{{ form.icon.help_text }} {% trans "If no symbol is selected, automatic detection determines the level in the diagram." %}</div>
|
||||||
{% for e in form.icon.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
|
{% for e in form.icon.errors %}<div class="text-danger small">{{ e }}</div>{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -58,8 +59,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="d-flex justify-content-end gap-2 mt-3">
|
<div class="d-flex justify-content-end gap-2 mt-3">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">Abbrechen</a>
|
<a href="{% url 'plugins:netbox_customer_export:symbol_list' %}" class="btn btn-outline-secondary">{% trans "Cancel" %}</a>
|
||||||
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> Speichern</button>
|
<button class="btn btn-primary"><i class="mdi mdi-content-save"></i> {% trans "Save" %}</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
{% extends 'generic/_base.html' %}
|
{% extends 'generic/_base.html' %}
|
||||||
{% block title %}Topologie-Symbole{% endblock %}
|
{% load i18n %}
|
||||||
|
{% block title %}{% trans "Topology Symbols" %}{% endblock %}
|
||||||
{% block controls %}
|
{% block controls %}
|
||||||
{% if perms.netbox_customer_export.add_topologysymbol %}
|
{% if perms.netbox_customer_export.add_topologysymbol %}
|
||||||
<div class="btn-list">
|
<div class="btn-list">
|
||||||
<a href="{% url 'plugins:netbox_customer_export:symbol_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> Zuordnung hinzufügen</a>
|
<a href="{% url 'plugins:netbox_customer_export:symbol_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick"></i> {% trans "Add assignment" %}</a>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -19,28 +20,28 @@
|
|||||||
<div class="row g-3 mt-1">
|
<div class="row g-3 mt-1">
|
||||||
<div class="col-xl-7">
|
<div class="col-xl-7">
|
||||||
<div class="card mb-3">
|
<div class="card mb-3">
|
||||||
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> Zuordnungen je Gerätetyp</h2>
|
<h2 class="card-header"><i class="mdi mdi-shape-outline"></i> {% trans "Assignments per device type" %}</h2>
|
||||||
{% include 'netbox_customer_export/_symbol_table.html' with rows=types empty="Noch keine Gerätetypen zugeordnet." %}
|
{% include 'netbox_customer_export/_symbol_table.html' with rows=types empty=_("No device types assigned yet.") %}
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="card-header"><i class="mdi mdi-tag-outline"></i> Zuordnungen je Geräterolle</h2>
|
<h2 class="card-header"><i class="mdi mdi-tag-outline"></i> {% trans "Assignments per device role" %}</h2>
|
||||||
{% include 'netbox_customer_export/_symbol_table.html' with rows=roles empty="Noch keine Geräterollen zugeordnet." %}
|
{% include 'netbox_customer_export/_symbol_table.html' with rows=roles empty=_("No device roles assigned yet.") %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-xl-5">
|
<div class="col-xl-5">
|
||||||
<div class="card mb-3">
|
<div class="card mb-3">
|
||||||
<h2 class="card-header"><i class="mdi mdi-information-outline"></i> So wird das Symbol bestimmt</h2>
|
<h2 class="card-header"><i class="mdi mdi-information-outline"></i> {% trans "How the symbol is determined" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<ol class="mb-0">
|
<ol class="mb-0">
|
||||||
<li><strong>Gerätetyp</strong>-Zuordnung (eigenes Icon oder Symbol)</li>
|
<li>{% blocktrans trimmed %}<strong>Device type</strong> assignment (custom icon or symbol){% endblocktrans %}</li>
|
||||||
<li><strong>Geräterolle</strong>-Zuordnung</li>
|
<li>{% blocktrans trimmed %}<strong>Device role</strong> assignment{% endblocktrans %}</li>
|
||||||
<li><strong>Automatisch</strong> anhand von Rolle, Modell und Hersteller, z.B. „Switch“, „Firewall“, „Sophos“, „Access Point“.
|
<li>{% blocktrans trimmed %}<strong>Automatic</strong> based on role, model and manufacturer, e.g. “Switch”, “Firewall”, “Sophos”, “Access Point”.
|
||||||
Patchpanels, Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet.</li>
|
Patch panels, power strips, PDUs and UPSs are hidden automatically.{% endblocktrans %}</li>
|
||||||
</ol>
|
</ol>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2 class="card-header"><i class="mdi mdi-view-grid-outline"></i> Eingebaute Symbole</h2>
|
<h2 class="card-header"><i class="mdi mdi-view-grid-outline"></i> {% trans "Built-in symbols" %}</h2>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="ce-gallery">
|
<div class="ce-gallery">
|
||||||
{% for key, label, url in builtin %}
|
{% for key, label, url in builtin %}
|
||||||
|
|||||||
+511
-170
@@ -1,13 +1,15 @@
|
|||||||
"""Netzwerk-Topologie: Graph aus den Kabelverbindungen, Ebenen-Layout, PNG- und draw.io-Ausgabe."""
|
"""Netzwerk-Topologie: Graph aus den Kabelverbindungen, Ebenen-Layout mit rechtwinkligen Leitungen, PNG-Ausgabe."""
|
||||||
import base64
|
import re
|
||||||
from collections import OrderedDict, defaultdict, deque
|
from collections import OrderedDict, defaultdict, deque
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from xml.sax.saxutils import escape, quoteattr
|
|
||||||
|
|
||||||
from .symbols import KINDS, SIZE, SymbolResolver, builtin_icon
|
from django.utils.translation import gettext as _
|
||||||
|
from django.utils.translation import ngettext
|
||||||
|
|
||||||
MAX_PER_ROW = 8
|
from .symbols import KINDS, SymbolResolver, builtin_icon
|
||||||
|
|
||||||
|
MAX_PER_ROW = 12 # breitere Zeilen werden umgebrochen
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -18,9 +20,10 @@ class Node:
|
|||||||
icon: bytes
|
icon: bytes
|
||||||
sub: list = field(default_factory=list)
|
sub: list = field(default_factory=list)
|
||||||
external: bool = False # Gerät eines anderen Standorts / Provider
|
external: bool = False # Gerät eines anderen Standorts / Provider
|
||||||
layer: int = 0
|
tier: int = None # Ebene überschreiben (sonst aus dem Symbol)
|
||||||
x: float = 0
|
row: int = 0 # Zeile im Diagramm (nach Umbruch)
|
||||||
y: float = 0
|
x: float = 0 # Mitte, in Layout-Pixeln
|
||||||
|
y: float = 0 # Oberkante des Symbols, wird beim Zeichnen gesetzt
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -28,6 +31,8 @@ class Edge:
|
|||||||
a: str
|
a: str
|
||||||
b: str
|
b: str
|
||||||
labels: list = field(default_factory=list)
|
labels: list = field(default_factory=list)
|
||||||
|
summary: str = "" # feste Beschriftung statt Port-Namen (z.B. Lokationsübersicht)
|
||||||
|
wireless: bool = False # nur Funkstrecken (WirelessLink) – blau gepunktet
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -39,24 +44,117 @@ class Graph:
|
|||||||
|
|
||||||
# --- Graph aufbauen -----------------------------------------------------------
|
# --- Graph aufbauen -----------------------------------------------------------
|
||||||
|
|
||||||
def _device_sub(device, details):
|
NAME_MAX = 15 # Zeichen je Zeile, z.B. „poller-thlg-ase“; längere Namen werden umgebrochen
|
||||||
|
|
||||||
|
|
||||||
|
def wrap_name(name, limit=NAME_MAX):
|
||||||
|
"""Namen in Zeilen zu höchstens `limit` Zeichen teilen, bevorzugt nach „-“, „_“, „.“ oder Leerzeichen."""
|
||||||
|
if len(name) <= limit:
|
||||||
|
return [name]
|
||||||
|
lines, cur = [], ""
|
||||||
|
for token in re.findall(r"[^-_. ]+[-_. ]*|[-_. ]+", name):
|
||||||
|
if len((cur + token).rstrip()) <= limit:
|
||||||
|
cur += token
|
||||||
|
continue
|
||||||
|
if cur.strip():
|
||||||
|
lines.append(cur.rstrip())
|
||||||
|
while len(token.rstrip()) > limit: # Wort ohne Trennzeichen: hart teilen
|
||||||
|
lines.append(token[:limit])
|
||||||
|
token = token[limit:]
|
||||||
|
cur = token
|
||||||
|
if cur.strip():
|
||||||
|
lines.append(cur.rstrip())
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def _device_sub(device, opts):
|
||||||
|
from .sections import ip_versions
|
||||||
|
|
||||||
|
details = set(opts.get("topo_details") or [])
|
||||||
sub = []
|
sub = []
|
||||||
if "model" in details:
|
if "model" in details:
|
||||||
sub.append(str(device.device_type.model))
|
sub.append(str(device.device_type.model))
|
||||||
if "primary_ip" in details and device.primary_ip:
|
if "primary_ip" in details:
|
||||||
sub.append(str(device.primary_ip.address.ip))
|
versions = ip_versions(opts)
|
||||||
|
for ip in (device.primary_ip4, device.primary_ip6):
|
||||||
|
if ip and ip.address.version in versions:
|
||||||
|
sub.append(str(ip.address.ip))
|
||||||
return sub
|
return sub
|
||||||
|
|
||||||
|
|
||||||
def build_graphs(scope, opts):
|
def build_graphs(scope, opts, per="site"):
|
||||||
"""Ein Graph je Standort. Geräte anderer Standorte und Provider-Leitungen erscheinen als externe Knoten."""
|
"""Ein Graph je Standort (per="site") oder je Rack (per="rack").
|
||||||
from dcim.models import Interface
|
|
||||||
|
Verbundene Geräte außerhalb der Gruppe (anderer Standort/anderes Rack) und Provider-Leitungen erscheinen
|
||||||
|
als externe, gestrichelte Knoten – so sieht man auch in der Rack-Ansicht, wohin die Uplinks gehen.
|
||||||
|
"""
|
||||||
|
cache = getattr(scope, "_topology_cache", None)
|
||||||
|
if cache is None:
|
||||||
|
cache = scope._topology_cache = _collect(scope, opts)
|
||||||
|
by_pk, drawn, links, external, wireless = cache
|
||||||
|
|
||||||
|
groups = OrderedDict()
|
||||||
|
for pk in drawn:
|
||||||
|
d = by_pk[pk]
|
||||||
|
key = d.site if per == "site" else d.rack
|
||||||
|
if key is not None:
|
||||||
|
groups.setdefault(key, []).append(pk)
|
||||||
|
if per == "rack":
|
||||||
|
groups = OrderedDict(
|
||||||
|
sorted(groups.items(), key=lambda kv: (str(kv[0].site), str(kv[0].location or ""), kv[0].name))
|
||||||
|
)
|
||||||
|
|
||||||
|
def context(d):
|
||||||
|
"""Untertitel eines externen Geräts: wo es steht."""
|
||||||
|
if per == "rack":
|
||||||
|
return [_("Rack %(name)s") % {"name": d.rack} if d.rack else str(d.site)]
|
||||||
|
return [str(d.site)]
|
||||||
|
|
||||||
|
graphs = []
|
||||||
|
for group, pks in groups.items():
|
||||||
|
nodes = OrderedDict()
|
||||||
|
for pk in pks:
|
||||||
|
d = by_pk[pk]
|
||||||
|
kind, icon = drawn[pk]
|
||||||
|
nodes[f"d{pk}"] = Node(f"d{pk}", d.name or str(d), kind, icon, _device_sub(d, opts))
|
||||||
|
members = set(nodes) # nur Geräte der Gruppe – externe Nachbarn ziehen keine weiteren Nachbarn nach
|
||||||
|
edges = []
|
||||||
|
for (a, b), labels in links.items():
|
||||||
|
in_a, in_b = a in members, b in members
|
||||||
|
if not (in_a or in_b):
|
||||||
|
continue
|
||||||
|
for nid, inside in ((a, in_a), (b, in_b)):
|
||||||
|
if not inside:
|
||||||
|
other = external.get(nid)
|
||||||
|
if other is None: # Gerät im selben Scope, aber anderer Standort / anderes Rack
|
||||||
|
d = by_pk[int(nid[1:])]
|
||||||
|
kind, icon = drawn[d.pk]
|
||||||
|
other = Node(nid, d.name or str(d), kind, icon, context(d), external=True)
|
||||||
|
nodes[nid] = Node(**{**other.__dict__})
|
||||||
|
edges.append(Edge(a, b, labels, wireless=(a, b) in wireless))
|
||||||
|
if not opts.get("topo_isolated"):
|
||||||
|
linked = {n for e in edges for n in (e.a, e.b)}
|
||||||
|
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
|
||||||
|
if nodes:
|
||||||
|
_layout(nodes, edges)
|
||||||
|
if per == "site":
|
||||||
|
title = _("Site %(name)s") % {"name": group}
|
||||||
|
else:
|
||||||
|
where = " / ".join(str(x) for x in (group.site, group.location) if x)
|
||||||
|
title = _("Rack %(name)s (%(where)s)") % {"name": group.name, "where": where}
|
||||||
|
graphs.append(Graph(title, nodes, edges))
|
||||||
|
return graphs
|
||||||
|
|
||||||
|
|
||||||
|
def _collect(scope, opts):
|
||||||
|
"""Geräte, Symbole und Verbindungen (Kabelpfade) des Scopes einmalig einlesen."""
|
||||||
|
from dcim.models import Interface
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
details = set(opts.get("topo_details") or [])
|
|
||||||
resolver = SymbolResolver()
|
resolver = SymbolResolver()
|
||||||
devices = list(
|
devices = list(
|
||||||
scope.devices().select_related(
|
scope.devices().select_related(
|
||||||
"role", "device_type__manufacturer", "site", "primary_ip4", "primary_ip6"
|
"role", "device_type__manufacturer", "site", "rack__site", "rack__location", "primary_ip4", "primary_ip6"
|
||||||
).order_by("site__name", "name")
|
).order_by("site__name", "name")
|
||||||
)
|
)
|
||||||
drawn = {} # device.pk -> (kind, icon)
|
drawn = {} # device.pk -> (kind, icon)
|
||||||
@@ -66,11 +164,12 @@ def build_graphs(scope, opts):
|
|||||||
drawn[d.pk] = (kind, icon)
|
drawn[d.pk] = (kind, icon)
|
||||||
by_pk = {d.pk: d for d in devices}
|
by_pk = {d.pk: d for d in devices}
|
||||||
|
|
||||||
# Verbindungen: vollständige Kabelpfade (auch über Patchpanels) zwischen Interfaces
|
# Verbindungen: vollständige Kabelpfade (auch über Patchpanels) und Funkstrecken zwischen Interfaces
|
||||||
links = defaultdict(list) # (a, b) -> ["Gi1/0/1 – eth0", …]
|
links = defaultdict(list) # (a, b) -> ["Gi1/0/1 – eth0", …]
|
||||||
|
kinds = defaultdict(set) # (a, b) -> {"cable", "wireless"}
|
||||||
external = {} # node_id -> Node-Vorlage
|
external = {} # node_id -> Node-Vorlage
|
||||||
ifaces = scope.restrict(
|
ifaces = scope.restrict(
|
||||||
Interface.objects.filter(device_id__in=list(drawn), cable__isnull=False)
|
Interface.objects.filter(Q(cable__isnull=False) | Q(wireless_link__isnull=False), device_id__in=list(drawn))
|
||||||
).select_related("device")
|
).select_related("device")
|
||||||
for iface in ifaces:
|
for iface in ifaces:
|
||||||
try:
|
try:
|
||||||
@@ -111,113 +210,278 @@ def build_graphs(scope, opts):
|
|||||||
label = " – ".join(reversed(label.split(" – ")))
|
label = " – ".join(reversed(label.split(" – ")))
|
||||||
if label not in links[key]:
|
if label not in links[key]:
|
||||||
links[key].append(label)
|
links[key].append(label)
|
||||||
|
kinds[key].add("cable" if iface.cable_id else "wireless")
|
||||||
|
|
||||||
# Knoten je Standort
|
wireless = {k for k, v in kinds.items() if v == {"wireless"}}
|
||||||
graphs = []
|
return by_pk, drawn, links, external, wireless
|
||||||
sites = OrderedDict()
|
|
||||||
for pk in drawn:
|
|
||||||
sites.setdefault(by_pk[pk].site, []).append(pk)
|
def build_location_graphs(scope, opts, combined=False):
|
||||||
for site, pks in sites.items():
|
"""Lokationsübersicht: ein Graph je Standort, Knoten = Lokationen, Linien = Kabel zwischen Lokationen.
|
||||||
nodes = OrderedDict()
|
|
||||||
for pk in pks:
|
Mit `combined=True` entsteht ein einziger standortübergreifender Graph über alle Lokationen im Scope, an
|
||||||
d = by_pk[pk]
|
jedem Knoten steht der Standort – so sieht man, wie Gebäude und ihre Lokationen untereinander verbunden sind.
|
||||||
kind, icon = drawn[pk]
|
|
||||||
nodes[f"d{pk}"] = Node(f"d{pk}", d.name or str(d), kind, icon, _device_sub(d, details))
|
Gezählt werden physische Kabel (Interfaces, Front- und Rear-Ports), deren Enden in verschiedenen Lokationen
|
||||||
edges = []
|
liegen – typischerweise LWL-/Kupfer-Trunks vom Serverraum zu den Unterverteilungen. Lokationen mit
|
||||||
for (a, b), labels in links.items():
|
Firewall/Router/Core stehen oben, die Ebenen darunter folgen der Verkabelung.
|
||||||
in_a, in_b = a in nodes, b in nodes
|
"""
|
||||||
if not (in_a or in_b):
|
from dcim.models import FrontPort, Interface, RearPort
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
|
resolver = SymbolResolver()
|
||||||
|
devices = list(
|
||||||
|
scope.devices()
|
||||||
|
.select_related("role", "device_type__manufacturer", "site", "location__parent", "rack")
|
||||||
|
.order_by("site__name", "location__name")
|
||||||
|
)
|
||||||
|
if not devices:
|
||||||
|
return []
|
||||||
|
by_pk = {d.pk: d for d in devices}
|
||||||
|
|
||||||
|
def node_of(d):
|
||||||
|
"""Lokation des Geräts – Geräte ohne Lokation (z.B. Richtfunk-APs am Dach) hängen am Standort selbst."""
|
||||||
|
return f"l{d.location_id}" if d.location_id else f"s{d.site_id}"
|
||||||
|
|
||||||
|
nid_of = {d.pk: node_of(d) for d in devices}
|
||||||
|
|
||||||
|
# Ebene je Lokation = „höchstes“ Gerät darin (Firewall/Core oben, reine Verteiler darunter)
|
||||||
|
tier, racks, count = {}, defaultdict(set), defaultdict(int)
|
||||||
|
for d in devices:
|
||||||
|
kind, _icon = resolver.resolve(d)
|
||||||
|
t = KINDS.get(kind, ("", 3))[1] if kind else 3
|
||||||
|
nid = nid_of[d.pk]
|
||||||
|
tier[nid] = min(tier.get(nid, 9), t)
|
||||||
|
count[nid] += 1
|
||||||
|
if d.rack_id:
|
||||||
|
racks[nid].add(d.rack_id)
|
||||||
|
|
||||||
|
cables = {} # ("c"|"w", pk) -> (Knoten a, Knoten b, Kabel oder WirelessLink)
|
||||||
|
outside = {} # node_id -> Node (andere Standorte / Provider)
|
||||||
|
for model in (Interface, FrontPort, RearPort):
|
||||||
|
cond = Q(cable__isnull=False)
|
||||||
|
if model is Interface:
|
||||||
|
cond |= Q(wireless_link__isnull=False)
|
||||||
|
ports = scope.restrict(model.objects.filter(cond, device_id__in=list(by_pk))).select_related("cable")
|
||||||
|
for port in ports:
|
||||||
|
link = port.cable if port.cable_id else port.wireless_link
|
||||||
|
link_key = ("c", port.cable_id) if port.cable_id else ("w", port.wireless_link_id)
|
||||||
|
if link_key in cables:
|
||||||
continue
|
continue
|
||||||
for nid, inside in ((a, in_a), (b, in_b)):
|
try:
|
||||||
if not inside:
|
peers = port.link_peers or []
|
||||||
other = external.get(nid)
|
except Exception: # noqa: BLE001
|
||||||
if other is None: # Gerät eines anderen Standorts im selben Scope
|
continue
|
||||||
d = by_pk[int(nid[1:])]
|
a = nid_of[port.device_id]
|
||||||
kind, icon = drawn[d.pk]
|
for peer in peers:
|
||||||
other = Node(nid, d.name or str(d), kind, icon, [str(d.site)], external=True)
|
peer_dev = getattr(peer, "device", None)
|
||||||
nodes[nid] = Node(**{**other.__dict__})
|
if peer_dev is not None:
|
||||||
edges.append(Edge(a, b, labels))
|
if peer_dev.pk in by_pk:
|
||||||
|
b = nid_of[peer_dev.pk]
|
||||||
|
elif not opts.get("topo_external"):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
loc = getattr(peer_dev, "location", None)
|
||||||
|
b = f"l{loc.pk}" if loc else f"s{peer_dev.site_id}"
|
||||||
|
outside[b] = Node(
|
||||||
|
b, str(loc or peer_dev.site), "location", builtin_icon("location"),
|
||||||
|
[str(peer_dev.site)], external=True,
|
||||||
|
)
|
||||||
|
elif peer._meta.model_name == "circuittermination" and opts.get("topo_external"):
|
||||||
|
circuit = peer.circuit
|
||||||
|
b = f"c{circuit.pk}"
|
||||||
|
outside[b] = Node(b, str(circuit.provider), "cloud", builtin_icon("cloud"), [str(circuit.cid)], external=True)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if a != b:
|
||||||
|
cables[link_key] = (a, b, link)
|
||||||
|
break
|
||||||
|
|
||||||
|
links = defaultdict(list)
|
||||||
|
for a, b, cable in cables.values():
|
||||||
|
links[tuple(sorted((a, b)))].append(cable)
|
||||||
|
|
||||||
|
sites = OrderedDict()
|
||||||
|
all_locs = {} # node_id -> (Name, Standort)
|
||||||
|
for d in devices:
|
||||||
|
nid = nid_of[d.pk]
|
||||||
|
sites.setdefault(None if combined else d.site, OrderedDict())[nid] = d
|
||||||
|
all_locs[nid] = (d.location.name if d.location_id else str(d.site), d.site)
|
||||||
|
|
||||||
|
graphs = []
|
||||||
|
for site, locations in sites.items():
|
||||||
|
nodes = OrderedDict()
|
||||||
|
for nid, d in locations.items():
|
||||||
|
loc = d.location
|
||||||
|
if loc is not None:
|
||||||
|
name = loc.name
|
||||||
|
where = [str(loc.site)] if combined else []
|
||||||
|
if loc.parent_id:
|
||||||
|
where.append(str(loc.parent))
|
||||||
|
else:
|
||||||
|
name = str(d.site)
|
||||||
|
where = [_("without location")]
|
||||||
|
sub = [" / ".join(where)] if where else []
|
||||||
|
n_racks, n_dev = len(racks[nid]), count[nid]
|
||||||
|
parts = [ngettext("%(n)d rack", "%(n)d racks", n_racks) % {"n": n_racks}] if n_racks else []
|
||||||
|
parts.append(ngettext("%(n)d device", "%(n)d devices", n_dev) % {"n": n_dev})
|
||||||
|
sub.append(" · ".join(parts))
|
||||||
|
nodes[nid] = Node(nid, name, "location", builtin_icon("location"), sub, tier=tier[nid])
|
||||||
|
members = set(nodes)
|
||||||
|
edges = []
|
||||||
|
for (a, b), lst in links.items():
|
||||||
|
if not (a in members or b in members):
|
||||||
|
continue
|
||||||
|
for nid in (a, b):
|
||||||
|
if nid in members:
|
||||||
|
continue
|
||||||
|
tpl = outside.get(nid)
|
||||||
|
if tpl is None: # Lokation im Scope, aber an einem anderen Standort
|
||||||
|
name, loc_site = all_locs[nid]
|
||||||
|
tpl = Node(nid, name, "location", builtin_icon("location"), [str(loc_site)], external=True)
|
||||||
|
nodes[nid] = Node(**{**tpl.__dict__})
|
||||||
|
edges.append(Edge(
|
||||||
|
a, b, [str(c) for c in lst], summary=_cable_summary(lst),
|
||||||
|
wireless=all(c._meta.model_name == "wirelesslink" for c in lst),
|
||||||
|
))
|
||||||
if not opts.get("topo_isolated"):
|
if not opts.get("topo_isolated"):
|
||||||
linked = {n for e in edges for n in (e.a, e.b)}
|
linked = {n for e in edges for n in (e.a, e.b)}
|
||||||
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
|
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
|
||||||
if nodes:
|
if nodes:
|
||||||
_layout(nodes, edges)
|
_layout(nodes, edges)
|
||||||
graphs.append(Graph(f"Standort {site}", nodes, edges))
|
title = _("All sites") if combined else _("Site %(name)s") % {"name": site}
|
||||||
|
graphs.append(Graph(title, nodes, edges))
|
||||||
return graphs
|
return graphs
|
||||||
|
|
||||||
|
|
||||||
|
def _cable_summary(cables):
|
||||||
|
"""„2× SMF, 4× CAT6a, 1× Funk“ – Kabel ohne Typ zählen als „Kabel“, Funkstrecken als „Funk“."""
|
||||||
|
types = defaultdict(int)
|
||||||
|
for c in cables:
|
||||||
|
if c._meta.model_name == "wirelesslink":
|
||||||
|
types[_("Wireless")] += 1
|
||||||
|
else:
|
||||||
|
types[c.get_type_display() if c.type else _("Cable")] += 1
|
||||||
|
return ", ".join(f"{n}× {t}" for t, n in sorted(types.items(), key=lambda x: -x[1]))
|
||||||
|
|
||||||
|
|
||||||
# --- Layout -------------------------------------------------------------------
|
# --- Layout -------------------------------------------------------------------
|
||||||
|
|
||||||
|
CELL_W = 174 # Spaltenbreite (enger = Symbole und Schrift im Dokument größer)
|
||||||
|
ICON = 64 # Symbolgröße
|
||||||
|
LANE = 11 # Abstand der Sammelschienen im Zwischenraum
|
||||||
|
PORT_H = 13 # Zeilenhöhe der Port-Beschriftungen
|
||||||
|
|
||||||
|
|
||||||
|
NAME_LINE_H = 15 # Zeilenhöhe des Gerätenamens
|
||||||
|
|
||||||
|
|
||||||
|
def _label_h(n):
|
||||||
|
return 20 + NAME_LINE_H * (len(wrap_name(n.label)) - 1) + 13 * len(n.sub)
|
||||||
|
|
||||||
|
|
||||||
def _layout(nodes, edges):
|
def _layout(nodes, edges):
|
||||||
"""Ebenen per Breitensuche ab den „höchsten“ Geräten (Provider, Firewall, Router …), dann Reihenfolge nach Nachbarn."""
|
"""Ebenen per Breitensuche ab den „höchsten“ Geräten (Provider, Firewall, Router …).
|
||||||
|
|
||||||
|
Die Breitensuche garantiert, dass verbundene Geräte höchstens eine Ebene auseinanderliegen – so bleiben
|
||||||
|
alle Leitungen kurz. Danach wird die Reihenfolge in mehreren Durchläufen (abwärts/aufwärts) nach dem
|
||||||
|
Schwerpunkt der Nachbarn sortiert, um Kreuzungen zu minimieren.
|
||||||
|
"""
|
||||||
adj = defaultdict(set)
|
adj = defaultdict(set)
|
||||||
for e in edges:
|
for e in edges:
|
||||||
adj[e.a].add(e.b)
|
adj[e.a].add(e.b)
|
||||||
adj[e.b].add(e.a)
|
adj[e.b].add(e.a)
|
||||||
tier = {nid: KINDS.get(n.kind, ("", 4))[1] for nid, n in nodes.items()}
|
tier = {nid: n.tier if n.tier is not None else KINDS.get(n.kind, ("", 4))[1] for nid, n in nodes.items()}
|
||||||
|
|
||||||
layer = {n: None for n in nodes if not adj[n]} # isolierte Knoten: unterste Zeile
|
layer = {n: None for n in nodes if not adj[n]} # isolierte Knoten: unterste Zeile
|
||||||
remaining = set(nodes) - set(layer)
|
remaining = set(nodes) - set(layer)
|
||||||
while remaining:
|
while remaining:
|
||||||
# jede Zusammenhangskomponente ab ihren am höchsten eingestuften Knoten
|
|
||||||
top = min(tier[n] for n in remaining)
|
top = min(tier[n] for n in remaining)
|
||||||
roots = [n for n in nodes if n in remaining and tier[n] == top]
|
|
||||||
queue = deque()
|
queue = deque()
|
||||||
for r in roots:
|
for r in [n for n in nodes if n in remaining and tier[n] == top]:
|
||||||
layer[r] = tier[r] if tier[r] <= 1 else 0
|
layer[r] = 0
|
||||||
queue.append(r)
|
queue.append(r)
|
||||||
while queue:
|
while queue:
|
||||||
cur = queue.popleft()
|
cur = queue.popleft()
|
||||||
remaining.discard(cur)
|
remaining.discard(cur)
|
||||||
for nb in adj[cur]:
|
for nb in adj[cur]:
|
||||||
if nb not in layer:
|
if nb not in layer:
|
||||||
layer[nb] = layer[cur] + 1 # Ebene folgt der Verkabelung
|
layer[nb] = layer[cur] + 1
|
||||||
queue.append(nb)
|
queue.append(nb)
|
||||||
|
|
||||||
used = sorted({v for v in layer.values() if v is not None})
|
used = sorted({v for v in layer.values() if v is not None})
|
||||||
rank = {v: i for i, v in enumerate(used)}
|
rank = {v: i for i, v in enumerate(used)}
|
||||||
bottom = len(used)
|
order = defaultdict(list)
|
||||||
rows = defaultdict(list)
|
|
||||||
for nid in nodes:
|
for nid in nodes:
|
||||||
rows[rank[layer[nid]] if layer[nid] is not None else bottom].append(nid)
|
order[rank[layer[nid]] if layer[nid] is not None else len(used)].append(nid)
|
||||||
|
rows = sorted(order)
|
||||||
|
|
||||||
# Reihenfolge: Schwerpunkt der Nachbarn in der Zeile darüber (reduziert Kreuzungen)
|
def centered(r):
|
||||||
pos = {}
|
row = order[r]
|
||||||
for r in sorted(rows):
|
return {n: i - (len(row) - 1) / 2 for i, n in enumerate(row)}
|
||||||
row = rows[r]
|
|
||||||
if r > 0:
|
|
||||||
def bary(n):
|
|
||||||
ps = [pos[p] for p in adj[n] if p in pos]
|
|
||||||
return sum(ps) / len(ps) if ps else 1e9
|
|
||||||
row.sort(key=bary)
|
|
||||||
for i, n in enumerate(row):
|
|
||||||
pos[n] = i
|
|
||||||
|
|
||||||
# Zeilen mit zu vielen Knoten umbrechen, dann Koordinaten
|
def sweep(r, ref):
|
||||||
CELL_W, CELL_H = 200, 190
|
if ref not in order:
|
||||||
|
return
|
||||||
|
pos, cur = centered(ref), centered(r)
|
||||||
|
|
||||||
|
def key(n):
|
||||||
|
ps = [pos[p] for p in adj[n] if p in pos]
|
||||||
|
return sum(ps) / len(ps) if ps else cur[n]
|
||||||
|
|
||||||
|
order[r].sort(key=key)
|
||||||
|
|
||||||
|
for _ in range(4):
|
||||||
|
for r in rows[1:]:
|
||||||
|
sweep(r, r - 1)
|
||||||
|
for r in reversed(rows[:-1]):
|
||||||
|
sweep(r, r + 1)
|
||||||
|
|
||||||
|
# Zeilen umbrechen und Spalten vergeben
|
||||||
lines = []
|
lines = []
|
||||||
for r in sorted(rows):
|
for r in rows:
|
||||||
row = rows[r]
|
row = order[r]
|
||||||
for i in range(0, len(row), MAX_PER_ROW):
|
for i in range(0, len(row), MAX_PER_ROW):
|
||||||
lines.append(row[i : i + MAX_PER_ROW])
|
lines.append(row[i : i + MAX_PER_ROW])
|
||||||
width = max(len(line) for line in lines) * CELL_W
|
width = max(len(line) for line in lines) * CELL_W
|
||||||
for li, line in enumerate(lines):
|
for li, line in enumerate(lines):
|
||||||
offset = (width - len(line) * CELL_W) / 2
|
offset = (width - len(line) * CELL_W) / 2
|
||||||
for i, nid in enumerate(line):
|
for i, nid in enumerate(line):
|
||||||
|
nodes[nid].row = li
|
||||||
nodes[nid].x = offset + i * CELL_W + CELL_W / 2
|
nodes[nid].x = offset + i * CELL_W + CELL_W / 2
|
||||||
nodes[nid].y = li * CELL_H + 70
|
|
||||||
|
|
||||||
|
|
||||||
def _oriented(graph, e):
|
def _oriented(graph, e):
|
||||||
"""Port-Beschriftungen aus Sicht des oberen Knotens („Uplink-Port – Downlink-Port“)."""
|
"""Port-Beschriftungen aus Sicht des oberen (bzw. linken) Knotens: „Uplink-Port – Downlink-Port“."""
|
||||||
a, b = graph.nodes[e.a], graph.nodes[e.b]
|
a, b = graph.nodes[e.a], graph.nodes[e.b]
|
||||||
if a.y <= b.y:
|
if (a.row, a.x) <= (b.row, b.x):
|
||||||
return e.labels
|
return e.labels
|
||||||
return [" – ".join(reversed(x.split(" – "))) for x in e.labels]
|
return [" – ".join(reversed(x.split(" – "))) for x in e.labels]
|
||||||
|
|
||||||
|
|
||||||
|
def _edge_text(graph, e, show_ports):
|
||||||
|
if e.summary:
|
||||||
|
return e.summary
|
||||||
|
if show_ports:
|
||||||
|
labels = _oriented(graph, e)
|
||||||
|
text = labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
|
||||||
|
return f"{_('Wireless')}: {text}" if e.wireless else text
|
||||||
|
count = f"{len(e.labels)}×" if len(e.labels) > 1 else ""
|
||||||
|
if e.wireless:
|
||||||
|
return f"{count} {_('Wireless')}".strip()
|
||||||
|
return count or None
|
||||||
|
|
||||||
|
|
||||||
# --- PNG ----------------------------------------------------------------------
|
# --- PNG ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
PALETTE = [
|
||||||
|
(31, 119, 180), (214, 39, 40), (44, 160, 44), (148, 103, 189), (255, 127, 14),
|
||||||
|
(23, 150, 170), (140, 86, 75), (188, 150, 20), (200, 80, 160), (90, 90, 90),
|
||||||
|
]
|
||||||
|
EXTERNAL = (160, 160, 160)
|
||||||
|
WIRELESS = (30, 136, 229) # Funkstrecken: blau, gepunktet
|
||||||
|
|
||||||
|
|
||||||
def _font(size, bold=False):
|
def _font(size, bold=False):
|
||||||
from PIL import ImageFont
|
from PIL import ImageFont
|
||||||
|
|
||||||
@@ -233,64 +497,191 @@ def _font(size, bold=False):
|
|||||||
return ImageFont.load_default()
|
return ImageFont.load_default()
|
||||||
|
|
||||||
|
|
||||||
|
def _plan(graph, show_ports):
|
||||||
|
"""Ordnet jede Verbindung einem Zwischenraum und einer Sammelschiene zu und berechnet die Zeilenhöhen."""
|
||||||
|
nodes = graph.nodes
|
||||||
|
rows = defaultdict(list)
|
||||||
|
for n in nodes.values():
|
||||||
|
rows[n.row].append(n)
|
||||||
|
n_rows = max(rows) + 1
|
||||||
|
|
||||||
|
down = defaultdict(lambda: defaultdict(list)) # Zwischenraum über Zeile r -> oberer Knoten -> [(Kind, Kante)]
|
||||||
|
same = defaultdict(list) # Zeile -> Kanten innerhalb der Zeile, nicht benachbart
|
||||||
|
direct = [] # benachbarte Knoten derselben Zeile: gerade Linie
|
||||||
|
for e in graph.edges:
|
||||||
|
a, b = nodes[e.a], nodes[e.b]
|
||||||
|
if a.row == b.row:
|
||||||
|
(direct if abs(a.x - b.x) <= CELL_W + 1 else same[a.row]).append(e)
|
||||||
|
else:
|
||||||
|
up, lo = (a, b) if a.row < b.row else (b, a)
|
||||||
|
down[lo.row][up.id].append((lo, e))
|
||||||
|
|
||||||
|
gaps = {}
|
||||||
|
for r in range(n_rows):
|
||||||
|
items = []
|
||||||
|
for uid, lst in down[r].items():
|
||||||
|
xs = [nodes[uid].x] + [c.x for c, _ in lst]
|
||||||
|
items.append((min(xs), max(xs), ("d", uid)))
|
||||||
|
for i, e in enumerate(same[r]):
|
||||||
|
xs = [nodes[e.a].x, nodes[e.b].x]
|
||||||
|
items.append((min(xs), max(xs), ("s", i)))
|
||||||
|
# Intervall-Färbung: überlappende Schienen bekommen verschiedene Höhen
|
||||||
|
lane_end, lane_of = [], {}
|
||||||
|
for xmin, xmax, key in sorted(items):
|
||||||
|
for li, end in enumerate(lane_end):
|
||||||
|
if end < xmin - 14:
|
||||||
|
lane_end[li], lane_of[key] = xmax, li
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
lane_of[key] = len(lane_end)
|
||||||
|
lane_end.append(xmax)
|
||||||
|
parents = defaultdict(list)
|
||||||
|
for uid, lst in down[r].items():
|
||||||
|
for c, e in lst:
|
||||||
|
parents[c.id].append(uid)
|
||||||
|
for c in parents:
|
||||||
|
parents[c].sort(key=lambda uid: nodes[uid].x)
|
||||||
|
labelled = [e for lst in down[r].values() for _, e in lst if _edge_text(graph, e, show_ports)]
|
||||||
|
stack = max((len(v) for v in parents.values()), default=0) if labelled else 0
|
||||||
|
label_room = stack * PORT_H + 4
|
||||||
|
height = 16 + len(lane_end) * LANE + label_room if lane_end else (26 if r else 12)
|
||||||
|
gaps[r] = {"lane_of": lane_of, "parents": parents, "height": height}
|
||||||
|
|
||||||
|
y = 16
|
||||||
|
for r in range(n_rows):
|
||||||
|
gaps[r]["top"] = y + 8
|
||||||
|
y += gaps[r]["height"]
|
||||||
|
for n in rows[r]:
|
||||||
|
n.y = y
|
||||||
|
y += ICON + max(_label_h(n) for n in rows[r])
|
||||||
|
width = max(n.x for n in nodes.values()) + CELL_W / 2
|
||||||
|
return down, same, direct, gaps, width, y + 16
|
||||||
|
|
||||||
|
|
||||||
def render_png(graph, show_ports=False, scale=2):
|
def render_png(graph, show_ports=False, scale=2):
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
icon = 64
|
nodes = graph.nodes
|
||||||
nodes = graph.nodes.values()
|
down, same, direct, gaps, width, height = _plan(graph, show_ports)
|
||||||
w = int((max(n.x for n in nodes) + 100) * scale)
|
S = scale
|
||||||
h = int((max(n.y for n in nodes) + 110) * scale)
|
img = Image.new("RGB", (int(width * S), int(height * S)), (255, 255, 255))
|
||||||
img = Image.new("RGB", (w, h), (255, 255, 255))
|
|
||||||
d = ImageDraw.Draw(img)
|
d = ImageDraw.Draw(img)
|
||||||
f_name, f_sub, f_port = _font(12 * scale, bold=True), _font(10 * scale), _font(8 * scale)
|
f_name, f_sub, f_port = _font(12 * S, bold=True), _font(10 * S), _font(8 * S)
|
||||||
|
|
||||||
def c(n):
|
def line(points, color, w=2, dashed=False):
|
||||||
return n.x * scale, n.y * scale
|
pts = [(x * S, y * S) for x, y in points]
|
||||||
|
if not dashed:
|
||||||
def anchors(a, b):
|
d.line(pts, fill=color, width=w * S, joint="curve")
|
||||||
"""Linie unterhalb der Beschriftung des oberen Knotens beginnen, oben am unteren Symbol enden."""
|
return
|
||||||
if a.y > b.y:
|
for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
|
||||||
a, b = b, a
|
length = max(abs(x2 - x1), abs(y2 - y1))
|
||||||
if a.y == b.y:
|
steps = max(int(length / (6 * S)), 1)
|
||||||
return c(a), c(b)
|
|
||||||
label_h = 22 + 13 * len(a.sub)
|
|
||||||
return (a.x * scale, (a.y + icon / 2 + label_h) * scale), (b.x * scale, (b.y - icon / 2 - 2) * scale)
|
|
||||||
|
|
||||||
for e in graph.edges:
|
|
||||||
a, b = graph.nodes[e.a], graph.nodes[e.b]
|
|
||||||
dashed = a.external or b.external
|
|
||||||
color = (150, 150, 150) if dashed else (60, 60, 60)
|
|
||||||
(x1, y1), (x2, y2) = anchors(a, b)
|
|
||||||
if dashed:
|
|
||||||
steps = int(max(abs(x2 - x1), abs(y2 - y1)) / (8 * scale)) or 1
|
|
||||||
for i in range(0, steps, 2):
|
for i in range(0, steps, 2):
|
||||||
t1, t2 = i / steps, min((i + 1) / steps, 1)
|
t1, t2 = i / steps, min((i + 1) / steps, 1)
|
||||||
d.line([(x1 + (x2 - x1) * t1, y1 + (y2 - y1) * t1), (x1 + (x2 - x1) * t2, y1 + (y2 - y1) * t2)], fill=color, width=2 * scale)
|
d.line(
|
||||||
else:
|
[(x1 + (x2 - x1) * t1, y1 + (y2 - y1) * t1), (x1 + (x2 - x1) * t2, y1 + (y2 - y1) * t2)],
|
||||||
d.line([(x1, y1), (x2, y2)], fill=color, width=2 * scale)
|
fill=color, width=w * S,
|
||||||
mx, my = (x1 + x2) / 2, (y1 + y2) / 2
|
)
|
||||||
text = None
|
|
||||||
if show_ports:
|
|
||||||
labels = _oriented(graph, e)
|
|
||||||
text = labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
|
|
||||||
elif len(e.labels) > 1:
|
|
||||||
text = f"{len(e.labels)}×"
|
|
||||||
if text:
|
|
||||||
tw = d.textlength(text, font=f_port)
|
|
||||||
d.rounded_rectangle([mx - tw / 2 - 4 * scale, my - 7 * scale, mx + tw / 2 + 4 * scale, my + 7 * scale], radius=3 * scale, fill=(255, 255, 255), outline=(200, 200, 200))
|
|
||||||
d.text((mx, my), text, fill=(40, 40, 40), font=f_port, anchor="mm")
|
|
||||||
|
|
||||||
for n in nodes:
|
def tag(text, x, y, anchor):
|
||||||
x, y = c(n)
|
text = _clip(d, text, f_port, (CELL_W - 12) * S)
|
||||||
pic = Image.open(BytesIO(n.icon)).convert("RGBA").resize((icon * scale, icon * scale), Image.LANCZOS)
|
tw = d.textlength(text, font=f_port)
|
||||||
|
cx = x * S
|
||||||
|
cy = y * S - (6 * S if anchor == "mb" else 0)
|
||||||
|
d.rounded_rectangle(
|
||||||
|
[cx - tw / 2 - 3 * S, cy - 6 * S, cx + tw / 2 + 3 * S, cy + 6 * S],
|
||||||
|
radius=2 * S, fill=(255, 255, 255), outline=(215, 215, 215),
|
||||||
|
)
|
||||||
|
d.text((cx, cy), text, fill=(40, 40, 40), font=f_port, anchor="mm")
|
||||||
|
|
||||||
|
colors = {}
|
||||||
|
|
||||||
|
def color_for(uid):
|
||||||
|
if uid not in colors:
|
||||||
|
colors[uid] = PALETTE[len(colors) % len(PALETTE)]
|
||||||
|
return colors[uid]
|
||||||
|
|
||||||
|
labels = [] # erst nach allen Linien zeichnen, damit sie oben liegen
|
||||||
|
|
||||||
|
for r, groups in sorted(down.items()):
|
||||||
|
gap = gaps[r]
|
||||||
|
for uid, lst in groups.items():
|
||||||
|
u = nodes[uid]
|
||||||
|
ly = gap["top"] + gap["lane_of"][("d", uid)] * LANE
|
||||||
|
col = EXTERNAL if u.external else color_for(uid)
|
||||||
|
entries = []
|
||||||
|
for c, e in lst:
|
||||||
|
plist = gap["parents"][c.id]
|
||||||
|
k = plist.index(uid)
|
||||||
|
# mehrere Uplinks in dasselbe Gerät: leicht versetzt einführen
|
||||||
|
entries.append((c, e, c.x + (k - (len(plist) - 1) / 2) * 9, len(plist) - 1 - k))
|
||||||
|
xs = [u.x] + [ex for _, _, ex, _ in entries]
|
||||||
|
u_bottom = u.y + ICON + _label_h(u) - 2
|
||||||
|
line([(u.x, u_bottom), (u.x, ly)], col, dashed=u.external)
|
||||||
|
if max(xs) > min(xs):
|
||||||
|
line([(min(xs), ly), (max(xs), ly)], col, dashed=u.external)
|
||||||
|
for c, e, ex, stack_pos in entries:
|
||||||
|
dashed = u.external or c.external
|
||||||
|
drop_col = WIRELESS if e.wireless else EXTERNAL if dashed else col
|
||||||
|
line([(ex, ly), (ex, c.y - 2)], drop_col, w=3 if len(e.labels) > 1 else 2, dashed=dashed or e.wireless)
|
||||||
|
if min(xs) < ex < max(xs): # Abzweig auf der Schiene markieren
|
||||||
|
d.ellipse([(ex - 2.5) * S, (ly - 2.5) * S, (ex + 2.5) * S, (ly + 2.5) * S], fill=col)
|
||||||
|
text = _edge_text(graph, e, show_ports)
|
||||||
|
if text:
|
||||||
|
labels.append((text, ex, c.y - 3 - stack_pos * PORT_H, "mb"))
|
||||||
|
|
||||||
|
for r, lst in same.items():
|
||||||
|
gap = gaps[r]
|
||||||
|
for i, e in enumerate(lst):
|
||||||
|
a, b = nodes[e.a], nodes[e.b]
|
||||||
|
ly = gap["top"] + gap["lane_of"][("s", i)] * LANE
|
||||||
|
dashed = a.external or b.external
|
||||||
|
col = WIRELESS if e.wireless else EXTERNAL if dashed else (70, 70, 70)
|
||||||
|
line([(a.x, a.y - 2), (a.x, ly), (b.x, ly), (b.x, b.y - 2)], col, dashed=dashed or e.wireless)
|
||||||
|
text = _edge_text(graph, e, show_ports)
|
||||||
|
if text:
|
||||||
|
labels.append((text, (a.x + b.x) / 2, ly, "mm"))
|
||||||
|
|
||||||
|
for e in direct:
|
||||||
|
a, b = nodes[e.a], nodes[e.b]
|
||||||
|
dashed = a.external or b.external
|
||||||
|
cy = a.y + ICON / 2
|
||||||
|
left, right = (a, b) if a.x < b.x else (b, a)
|
||||||
|
line(
|
||||||
|
[(left.x + ICON / 2 + 4, cy), (right.x - ICON / 2 - 4, cy)],
|
||||||
|
WIRELESS if e.wireless else EXTERNAL if dashed else (70, 70, 70),
|
||||||
|
w=3 if len(e.labels) > 1 else 2, dashed=dashed or e.wireless,
|
||||||
|
)
|
||||||
|
text = _edge_text(graph, e, show_ports)
|
||||||
|
if text:
|
||||||
|
labels.append((text, (a.x + b.x) / 2, cy - 4, "mb"))
|
||||||
|
|
||||||
|
for n in nodes.values():
|
||||||
|
pic = Image.open(BytesIO(n.icon)).convert("RGBA").resize((ICON * S, ICON * S), Image.LANCZOS)
|
||||||
if n.external:
|
if n.external:
|
||||||
alpha = pic.getchannel("A").point(lambda v: int(v * 0.55))
|
pic.putalpha(pic.getchannel("A").point(lambda v: int(v * 0.5)))
|
||||||
pic.putalpha(alpha)
|
img.paste(pic, (int((n.x - ICON / 2) * S), int(n.y * S)), pic)
|
||||||
img.paste(pic, (int(x - icon * scale / 2), int(y - icon * scale / 2)), pic)
|
ty = (n.y + ICON + 3) * S
|
||||||
ty = y + icon * scale / 2 + 4 * scale
|
name_lines = wrap_name(n.label)
|
||||||
d.text((x, ty), _clip(d, n.label, f_name, 190 * scale), fill=(110, 110, 110) if n.external else (20, 20, 20), font=f_name, anchor="ma")
|
for i, part in enumerate(name_lines):
|
||||||
for i, line in enumerate(n.sub):
|
d.text(
|
||||||
d.text((x, ty + (16 + i * 13) * scale), _clip(d, line, f_sub, 190 * scale), fill=(100, 100, 100), font=f_sub, anchor="ma")
|
(n.x * S, ty + i * NAME_LINE_H * S), _clip(d, part, f_name, (CELL_W - 8) * S),
|
||||||
|
fill=(120, 120, 120) if n.external else (20, 20, 20), font=f_name, anchor="ma",
|
||||||
|
)
|
||||||
|
sub_y = ty + (16 + NAME_LINE_H * (len(name_lines) - 1)) * S
|
||||||
|
for i, sub in enumerate(n.sub):
|
||||||
|
d.text((n.x * S, sub_y + i * 13 * S), _clip(d, sub, f_sub, (CELL_W - 8) * S), fill=(100, 100, 100), font=f_sub, anchor="ma")
|
||||||
|
|
||||||
|
for text, x, y, anchor in labels:
|
||||||
|
tag(text, x, y, anchor)
|
||||||
|
|
||||||
|
# weißen Rand abschneiden: jeder Millimeter kommt der Größe im Dokument zugute
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
bbox = ImageChops.difference(img, Image.new("RGB", img.size, (255, 255, 255))).getbbox()
|
||||||
|
if bbox:
|
||||||
|
pad = 6 * S
|
||||||
|
img = img.crop((max(bbox[0] - pad, 0), max(bbox[1] - pad, 0), min(bbox[2] + pad, img.width), min(bbox[3] + pad, img.height)))
|
||||||
|
|
||||||
out = BytesIO()
|
out = BytesIO()
|
||||||
img.save(out, "PNG", optimize=True)
|
img.save(out, "PNG", optimize=True)
|
||||||
@@ -303,53 +694,3 @@ def _clip(d, text, font, width):
|
|||||||
while text and d.textlength(text + "…", font=font) > width:
|
while text and d.textlength(text + "…", font=font) > width:
|
||||||
text = text[:-1]
|
text = text[:-1]
|
||||||
return text + "…"
|
return text + "…"
|
||||||
|
|
||||||
|
|
||||||
# --- draw.io ------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _small_icon(png, px=64):
|
|
||||||
from PIL import Image
|
|
||||||
|
|
||||||
img = Image.open(BytesIO(png)).convert("RGBA").resize((px, px), Image.LANCZOS)
|
|
||||||
out = BytesIO()
|
|
||||||
img.save(out, "PNG", optimize=True)
|
|
||||||
return base64.b64encode(out.getvalue()).decode("ascii")
|
|
||||||
|
|
||||||
|
|
||||||
def render_drawio(graphs, show_ports=False):
|
|
||||||
"""draw.io-Datei (mxfile) mit einer Seite je Standort. Symbole als eingebettete Bilder."""
|
|
||||||
icon_cache = {}
|
|
||||||
pages = []
|
|
||||||
for gi, g in enumerate(graphs):
|
|
||||||
cells = ['<mxCell id="0"/>', '<mxCell id="1" parent="0"/>']
|
|
||||||
for n in g.nodes.values():
|
|
||||||
key = id(n.icon)
|
|
||||||
if key not in icon_cache:
|
|
||||||
icon_cache[key] = _small_icon(n.icon)
|
|
||||||
label = escape(n.label) + "".join(f"<br><font style=\"font-size:10px\" color=\"#666666\">{escape(s)}</font>" for s in n.sub)
|
|
||||||
style = (
|
|
||||||
"shape=image;html=1;verticalLabelPosition=bottom;verticalAlign=top;labelBackgroundColor=none;"
|
|
||||||
f"imageAspect=0;aspect=fixed;fontStyle=1;{'opacity=55;' if n.external else ''}"
|
|
||||||
f"image=data:image/png,{icon_cache[key]};"
|
|
||||||
)
|
|
||||||
cells.append(
|
|
||||||
f'<mxCell id="{n.id}" value={quoteattr(label)} style={quoteattr(style)} vertex="1" parent="1">'
|
|
||||||
f'<mxGeometry x="{n.x - 32:.0f}" y="{n.y - 32:.0f}" width="64" height="64" as="geometry"/></mxCell>'
|
|
||||||
)
|
|
||||||
for i, e in enumerate(g.edges):
|
|
||||||
dashed = g.nodes[e.a].external or g.nodes[e.b].external
|
|
||||||
label = "<br>".join(escape(x) for x in _oriented(g, e)) if show_ports else (f"{len(e.labels)}×" if len(e.labels) > 1 else "")
|
|
||||||
style = f"endArrow=none;html=1;strokeWidth=2;strokeColor={'#999999' if dashed else '#333333'};{'dashed=1;' if dashed else ''}fontSize=9;labelBackgroundColor=#ffffff;"
|
|
||||||
cells.append(
|
|
||||||
f'<mxCell id="e{i}" value={quoteattr(label)} style={quoteattr(style)} edge="1" parent="1" source="{e.a}" target="{e.b}">'
|
|
||||||
'<mxGeometry relative="1" as="geometry"/></mxCell>'
|
|
||||||
)
|
|
||||||
pages.append(
|
|
||||||
f'<diagram id="page{gi}" name={quoteattr(g.title)}><mxGraphModel dx="1200" dy="800" grid="1" gridSize="10" '
|
|
||||||
f'guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" math="0" shadow="0">'
|
|
||||||
f'<root>{"".join(cells)}</root></mxGraphModel></diagram>'
|
|
||||||
)
|
|
||||||
return f'<mxfile host="netbox-customer-export">{"".join(pages)}</mxfile>'.encode("utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = ["build_graphs", "render_png", "render_drawio", "SIZE"]
|
|
||||||
@@ -3,6 +3,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin
|
|||||||
from django.http import Http404, HttpResponse
|
from django.http import Http404, HttpResponse
|
||||||
from django.shortcuts import get_object_or_404, redirect, render
|
from django.shortcuts import get_object_or_404, redirect, render
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
from django.utils.formats import date_format
|
||||||
from django.utils.text import slugify
|
from django.utils.text import slugify
|
||||||
from django.views import View
|
from django.views import View
|
||||||
|
|
||||||
@@ -28,20 +29,6 @@ class ScopeSelectView(LoginRequiredMixin, View):
|
|||||||
|
|
||||||
|
|
||||||
class ExportView(LoginRequiredMixin, View):
|
class ExportView(LoginRequiredMixin, View):
|
||||||
def _drawio(self, request, scope, form, opts):
|
|
||||||
"""Nur die Topologie – als editierbare draw.io-Datei (eine Seite je Standort)."""
|
|
||||||
from .topology import build_graphs, render_drawio
|
|
||||||
|
|
||||||
graphs = build_graphs(scope, opts)
|
|
||||||
if not graphs:
|
|
||||||
messages.warning(request, "Keine verkabelten Geräte gefunden – es gibt keine Topologie zu exportieren.")
|
|
||||||
return self._render_form(request, scope, form)
|
|
||||||
content = render_drawio(graphs, show_ports="ports" in (opts.get("topo_details") or []))
|
|
||||||
response = HttpResponse(content, content_type="application/xml")
|
|
||||||
filename = f"topologie_{slugify(str(scope.obj)) or 'export'}_{timezone.localdate():%Y%m%d}.drawio"
|
|
||||||
response["Content-Disposition"] = f'attachment; filename="{filename}"'
|
|
||||||
return response
|
|
||||||
|
|
||||||
template_name = "netbox_customer_export/export.html"
|
template_name = "netbox_customer_export/export.html"
|
||||||
|
|
||||||
def _scope(self, request, kind, pk):
|
def _scope(self, request, kind, pk):
|
||||||
@@ -55,7 +42,9 @@ class ExportView(LoginRequiredMixin, View):
|
|||||||
grouped = {}
|
grouped = {}
|
||||||
for s in SECTIONS.values():
|
for s in SECTIONS.values():
|
||||||
grouped.setdefault(s.group, []).append(s)
|
grouped.setdefault(s.group, []).append(s)
|
||||||
return render(request, self.template_name, {"object": scope.obj, "scope": scope, "form": form, "section_groups": grouped})
|
return render(request, self.template_name, {
|
||||||
|
"object": scope.obj, "scope": scope, "form": form, "section_groups": grouped, "rack_photos": form.photo_groups,
|
||||||
|
})
|
||||||
|
|
||||||
def get(self, request, kind, pk):
|
def get(self, request, kind, pk):
|
||||||
scope = self._scope(request, kind, pk)
|
scope = self._scope(request, kind, pk)
|
||||||
@@ -68,11 +57,10 @@ class ExportView(LoginRequiredMixin, View):
|
|||||||
return self._render_form(request, scope, form)
|
return self._render_form(request, scope, form)
|
||||||
|
|
||||||
opts = form.cleaned_data
|
opts = form.cleaned_data
|
||||||
if opts["format"] == "drawio":
|
|
||||||
return self._drawio(request, scope, form, opts)
|
|
||||||
blocks = []
|
blocks = []
|
||||||
for key in opts["sections"]:
|
for key in opts["sections"]:
|
||||||
blocks += SECTIONS[key].func(scope, opts)
|
blocks += SECTIONS[key].func(scope, opts)
|
||||||
|
blocks += opts.pop("_appendix", []) # z.B. Rack-Fotos, immer am Dokumentende
|
||||||
|
|
||||||
doc = Document(
|
doc = Document(
|
||||||
title=opts["title"],
|
title=opts["title"],
|
||||||
@@ -80,7 +68,7 @@ class ExportView(LoginRequiredMixin, View):
|
|||||||
blocks=blocks,
|
blocks=blocks,
|
||||||
meta={
|
meta={
|
||||||
"author": opts.get("author") or request.user.get_full_name() or request.user.username,
|
"author": opts.get("author") or request.user.get_full_name() or request.user.username,
|
||||||
"date": timezone.localtime().strftime("%d.%m.%Y"),
|
"date": date_format(timezone.localdate(), "SHORT_DATE_FORMAT"),
|
||||||
},
|
},
|
||||||
branding=get_branding(opts["branding"]),
|
branding=get_branding(opts["branding"]),
|
||||||
)
|
)
|
||||||
@@ -92,6 +80,6 @@ class ExportView(LoginRequiredMixin, View):
|
|||||||
|
|
||||||
response = HttpResponse(content, content_type=content_type)
|
response = HttpResponse(content, content_type=content_type)
|
||||||
if ext != "html":
|
if ext != "html":
|
||||||
filename = f"{slugify(opts['title']) or 'dokumentation'}_{timezone.localdate():%Y%m%d}.{ext}"
|
filename = f"{slugify(opts['title']) or 'documentation'}_{timezone.localdate():%Y%m%d}.{ext}"
|
||||||
response["Content-Disposition"] = f'attachment; filename="{filename}"'
|
response["Content-Disposition"] = f'attachment; filename="{filename}"'
|
||||||
return response
|
return response
|
||||||
+7
-3
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "netbox-customer-export"
|
name = "netbox-customer-export"
|
||||||
version = "0.4.0"
|
version = "0.19.1"
|
||||||
description = "NetBox-Plugin: Kundendokumentation (PDF/Word) für Standorte, Lokationen, Mandanten und Mandantengruppen"
|
description = "NetBox plugin: customer documentation (PDF/Word) for sites, locations, tenants and tenant groups"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
license = { text = "Apache-2.0" }
|
license = { text = "Apache-2.0" }
|
||||||
@@ -20,4 +20,8 @@ all = ["weasyprint>=62", "python-docx>=1.1", "cairosvg>=2.7"]
|
|||||||
include = ["netbox_customer_export*"]
|
include = ["netbox_customer_export*"]
|
||||||
|
|
||||||
[tool.setuptools.package-data]
|
[tool.setuptools.package-data]
|
||||||
netbox_customer_export = ["templates/**/*.html"]
|
netbox_customer_export = [
|
||||||
|
"templates/**/*.html",
|
||||||
|
"locale/*/LC_MESSAGES/*.po",
|
||||||
|
"locale/*/LC_MESSAGES/*.mo",
|
||||||
|
]
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Keeps the README compatibility table in sync with the PluginConfig version range."""
|
||||||
|
import ast
|
||||||
|
import re
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def plugin_versions():
|
||||||
|
tree = ast.parse((ROOT / "netbox_customer_export" / "__init__.py").read_text())
|
||||||
|
values = {}
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant):
|
||||||
|
for target in node.targets:
|
||||||
|
if isinstance(target, ast.Name) and target.id in ("min_version", "max_version"):
|
||||||
|
values[target.id] = node.value.value
|
||||||
|
return values["min_version"], values["max_version"]
|
||||||
|
|
||||||
|
|
||||||
|
def readme_range(max_version):
|
||||||
|
# "4.7.99" is documented as "4.7.x"
|
||||||
|
major_minor, patch = max_version.rsplit(".", 1)
|
||||||
|
return major_minor + ".x" if patch == "99" else max_version
|
||||||
|
|
||||||
|
|
||||||
|
class MetadataTest(unittest.TestCase):
|
||||||
|
def test_readme_matches_plugin_config(self):
|
||||||
|
min_version, max_version = plugin_versions()
|
||||||
|
expected = f"`{min_version}` – `{readme_range(max_version)}`"
|
||||||
|
readme = (ROOT / "README.md").read_text()
|
||||||
|
self.assertIn(f"| **NetBox** | {expected} |", readme)
|
||||||
|
self.assertRegex(readme, re.escape(f"- NetBox {expected}"))
|
||||||
|
|
||||||
|
def test_package_ships_translations(self):
|
||||||
|
pyproject = (ROOT / "pyproject.toml").read_text()
|
||||||
|
self.assertIn("locale/*/LC_MESSAGES/*.mo", pyproject)
|
||||||
|
self.assertTrue((ROOT / "netbox_customer_export" / "locale" / "de" / "LC_MESSAGES" / "django.mo").exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user