Compare commits

...
32 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 f557e7d49d feat(i18n): use English source strings with German translation
Wrap all user-visible strings for translation, ship a complete German catalogue, align the NetBox version range (4.4.0-4.7.x) with the README and add a test that keeps them in sync.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 21:28:37 +01:00
MrBlakeandClaude Opus 5.5 e6995630e9 docs: add screenshots and generalise README
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:58:10 +01:00
MrBlakeandClaude Opus 5.5 80a0e44bad Add missing migration for tags fields
The initial migrations declared tags as a plain ManyToManyField, while NetBoxModel uses a TaggableManager via extras.TaggedItem. Align the migration state. Verified with NetBox 4.7.2. Bump version to 0.12.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 14:13:27 +02:00
MrBlakeandClaude Opus 5.5 f7e1e21c24 feat: VS Code-like syntax highlighting for code blocks
Code blocks in documents are now highlighted server-side with Pygments
according to their language (Markdown fences and TinyMCE code samples),
using VS Code "Dark+" colours in the viewer and a light variant in the
print view. A language label is shown next to the copy button. Blocks
marked as plain text/Cisco config stay unchanged; blocks without a
language are only coloured when the language is detected confidently.
Works offline, no CDN needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 12:17:25 +02:00
MrBlakeandClaude Opus 5.5 8458cbe8cf fix: allow moving documents into any folder regardless of tenant
Drag & drop no longer rejects folders that belong to another tenant.
Moving only changes the document's folder; its tenant stays untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 11:40:58 +02:00
MrBlakeandClaude Opus 5.5 de8d13aec1 feat: move documents between folders via drag & drop in Explorer
Documents can be dragged onto folder tiles, entries in the navigation
pane, address bar segments or the empty area of the open folder. The
new document_move endpoint updates only the folder (with change log
entry) and rejects targets whose folder belongs to another tenant, so
a document always stays in its tenant. Invalid targets are highlighted
red while dragging; the result is shown as a toast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 11:37:12 +02:00
MrBlakeandClaude Opus 5.5 2cb7878351 feat: add right-click context menu to the documentation Explorer
Right-clicking a folder, a document, a navigation entry or the empty
area of the open folder shows a context menu: open, open in new tab,
rename/edit, delete, new subfolder/document, export folder as ZIP,
print/PDF export, copy link and refresh. Entries respect the user's
permissions and return to the current folder afterwards. The menu also
opens via the context-menu key or Shift+F10 and supports arrow keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 11:33:03 +02:00
MrBlakeandClaude Opus 5.5 5656512973 feat: create folders and documents in the open Explorer folder
Add a "Neuer Ordner" button next to "Hinzufügen" in the documentation
view. Both buttons follow the folder currently open in the Explorer:
the new folder gets it as parent, a new document gets it as folder.
After saving, the user returns to that same folder (?folder=<pk>).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 11:26:25 +02:00
MrBlakeandClaude Opus 5.5 65d1f740ac feat: search across all folders in Explorer view
The Explorer search now matches folders and documents in every folder
instead of only the open one. Results are shown as tiles labelled with
their folder path; clicking a folder result clears the search and
opens that folder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-05 12:22:48 +02:00
MrBlakeandClaude Opus 5.5 78d60bd0ef feat: add Windows Explorer-style view for documentation
Show documentation in an Explorer-like layout: a folder navigation
pane on the left, folder and document tiles with large icons on the
right, plus back/up buttons, a clickable address bar and a status bar.
A view switcher (Explorer | Tree | List) lets users go back to the
previous tree view; the chosen view is remembered in localStorage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-05 12:14:03 +02:00
MrBlakeandClaude Opus 5.5 3423e18a1d fix: Syntaxfehler im Kopieren-Button der Code-Bloecke beheben
Ein Zeilenumbruch im Regex-Literal hat das Skript der Dokumentansicht
abbrechen lassen, sodass kein Kopieren-Button erschien. Version auf
0.12.0 angehoben.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 09:17:09 +02:00
MrBlakeandClaude Opus 5.5 d426f50f41 feat: Code-Bloecke mit Kopieren-Button und Code-Beispiel-Editor
Im Editor gibt es jetzt das TinyMCE-Plugin "codesample", um Code-
Bloecke ohne Markdown/HTML einzufuegen. In der Ansicht erhalten
Code-Bloecke ein einheitliches dunkles Layout, eine gut sichtbare
Textmarkierung (eingefuegte Inline-Hintergruende werden ignoriert)
und einen Kopieren-Button mit Fallback fuer Umgebungen ohne
Clipboard-API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 09:13:12 +02:00
MrBlakeandClaude Opus 5.5 dce3d83fd2 docs: rewrite README in English with standard structure
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 13:36:54 +02:00
MrBlakeandClaude Sonnet 5 d4fc8d1ab9 fix: globalen Mandantenfilter in Ordner-/Dokumentenbaum respektieren
Die Baumansichten (DocumentTreeView, DocumentCategoryTreeView) bauen
ihr Queryset manuell statt ueber ein NetBoxModelFilterSet, wodurch das
netbox-utilities-Plugin seinen tenant_id/tenant_group_id-Parameter nicht
injizieren konnte und ausserhalb des gewaehlten Mandanten liegende
Ordner/Dokumente mit angezeigt wurden. Liest jetzt den oeffentlichen
Scope aus netbox_utilities.tenant_scope direkt aus (fallback: kein
Filter, falls das Plugin nicht installiert ist).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:22:10 +02:00
MrBlakeandClaude Sonnet 5 359f752031 feat: Dokumentationen als Explorer-artigen Ordnerbaum anzeigen
Neue Standardansicht fuer "Dokumentationen" im Windows-Explorer/
Nextcloud-Stil: Ordner und Unterordner als aufklappbarer Baum mit
den zugehoerigen Dokumenten als Dateien darin, inkl. Live-Suche.
Die bisherige Tabellenansicht bleibt als "Listenansicht" erreichbar.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:07:04 +02:00
MrBlakeandClaude Sonnet 5 69f3d0af18 feat: Ordner als echten verschachtelten Baum statt Flachliste anzeigen
Neue Baumansicht fuer Ordner & Kategorien im Nextcloud/Bookstack-Stil
mit Klapp-Navigation, Live-Suche und Breadcrumb-Pfad auf der
Ordner-Detailseite. Die bisherige Tabellenansicht bleibt fuer
Bulk-Aktionen als "Listenansicht" erhalten.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-17 10:00:42 +02:00
MrBlake e54917a34c docs: Aktualisierung über HTTPS-Git dokumentieren 2026-09-02 10:52:39 +02:00
MrBlake 90787fd360 fix: Mandant vor erstem Speichern importierter Ordner setzen 2026-09-02 10:49:03 +02:00
MrBlake 1e670b1148 fix: Import mit fehlendem Mandanten laut abbrechen statt still verwerfen
Beim ZIP-Import wurden Tenant/TenantGroup bisher per Slug per
.filter().first() aufgelöst. Existierte der referenzierte Mandant auf
der Zielinstanz nicht, wurde das Feld stillschweigend auf None gesetzt.
Das führte bei Instanzen mit Mandanten-Pflichtfeld-Validierung zu einer
generischen ValidationError beim document.save(), ohne Hinweis darauf,
welches Dokument oder welcher Mandant betroffen war.

_resolve_tenant()/_resolve_tenant_group() werfen nun eine ArchiveFailure
mit Dokument-/Ordnertitel und fehlendem Slug, sobald ein referenzierter
Mandant nicht gefunden wird.
2026-09-02 10:41:52 +02:00
MrBlake 117ffac210 feat: Mandantenauswahl nach Mandantengruppe filtern 2026-07-29 10:28:52 +02:00
MrBlake 2af5ea997d fix: Mandantenvalidierung mit NetBox 4.6 kompatibel machen 2026-07-29 10:24:44 +02:00
MrBlake 791b40b3c4 feat: Mandantenzuordnung für Dokumente und Ordner ergänzen 2026-07-29 10:17:18 +02:00
MrBlake d20baa3ea3 feat: lokale Bildauswahl im Editor ergänzen 2026-07-24 11:30:33 +02:00
MrBlake b632a5bb04 fix: eingefügte Bilder beim ersten Speichern dauerhaft ablegen 2026-07-23 16:36:07 +02:00
MrBlake 8d6b6a46db feat: gleichnamige Dokumentationen nach Bestätigung aktualisieren 2026-07-23 16:20:14 +02:00
MrBlake 83cac4447a feat: Querformat für Druck- und PDF-Ansicht ergänzen 2026-07-23 16:15:01 +02:00
MrBlake dbf3e7a62a fix: Farben freier Excel-Zellen beim Glätten bewahren 2026-07-23 16:13:38 +02:00
MrBlake 4690e67b32 perf: nur ausgewählte Excel-Blätter vollständig importieren 2026-07-23 16:03:56 +02:00
MrBlake 214502277f fix: Tabellenfarben beim geglätteten Excel-Import erhalten 2026-07-23 15:57:28 +02:00
MrBlake 5e17e9ecdb fix: Excel-Tabellenfarben in Importvorschau darstellen 2026-07-23 15:53:15 +02:00
MrBlake 3f2e7ca667 perf: Mehrblattimport großer Excel-Dateien optimieren 2026-07-23 15:48:07 +02:00
MrBlake e4f4cd7c14 fix: Excel-Zellfarben beim Dokumentimport erhalten 2026-07-23 15:44:58 +02:00
44 changed files with 3688 additions and 394 deletions

No files matched your search

+201 -91
View File
@@ -1,72 +1,90 @@
# NetBox Documentation
Ein in NetBox integriertes Markdown-Wiki für Betriebsdokumentationen und Anleitungen.
A wiki for operational documentation and how-tos, integrated into NetBox.
## Funktionen
| | |
|---|---|
| **Plugin name** | `netbox_documentation` |
| **Package** | `netbox-documentation` |
| **NetBox** | `4.4.0` – `4.7.x` |
| **Python** | `>=3.10` |
| **Repository** | <https://git.mrblake.cc/MrBlake/Netbox-Documentation> |
- Dokumentationen direkt in NetBox schreiben und als sicher bereinigten Rich Text anzeigen
- Word-ähnlicher WYSIWYG-Editor mit Schriftarten, Schriftgrößen, Farben, Ausrichtung und Tabellen
- Hierarchische Ordner und Unterordner für eine BookStack-ähnliche Struktur
- Breite Editoransicht und Fokusmodus innerhalb des NetBox-Layouts
- Bilder direkt vom eigenen Gerät in die Dokumentation hochladen
- Formatierte Word-Inhalte inklusive Tabellen und unterstützten Zwischenablage-Bildern einfügen
- Mehrere Dokumentationen mit Ordnern, Zuordnungen und Anhängen als ZIP exportieren und wieder importieren
- Druckoptimierte A4-Ansicht zum Drucken oder Speichern als PDF
- Seitenfüllende Großansicht per Schaltfläche oder Klick auf eine Tabelle
- Lesbare Tabellen mit vollständigen Zellrahmen und horizontalem Inhalts-Scrolling
- Tabellen-Presets, farbige Kopfzeilen und Zellhervorhebungen im WYSIWYG-Editor
- Excel-Mehrblattimport: je Arbeitsblatt eine Dokumentation in einem gewählten Zielordner
- Zweistufige Excel-Vorschau mit Blattauswahl und frei änderbaren Dokumenttiteln
- Optionales Glätten von Excel-Tabellen in kompakte Feld-/Wert-Textblöcke
- Eine Dokumentation mehreren Objekten zuordnen und umgekehrt
- Unbegrenzt viele Objektzuordnungen pro Dokumentation; nur identische Doppelzuordnungen werden verhindert
- Unterstützte Standardobjekte: Region, Standort, Location, Rack, Gerät, VM, VM-Cluster und Mandant/Kunde
- DOCX, XLSX/XLSM, textbasierte PDF-, Markdown- und Textdateien importieren
- Originaldatei optional zusammen mit der Dokumentation aufbewahren
- Dokumentationen über die globale NetBox-Suche und per REST-API finden
- NetBox-Berechtigungen, Änderungsprotokoll, Tags und Custom Fields verwenden
## Screenshots
## Kompatibilität
Document with tenant, folder and object assignments:
Die Version `0.7.0` zielt auf NetBox 4.x (mindestens 4.0). Vor einem produktiven Rollout sollte das Plugin gegen die konkret eingesetzte NetBox-Minor-Version in einer Testinstanz geprüft werden.
![Document with tenant, folder and object assignments](docs/screenshots/document.png)
Document list:
![Document list](docs/screenshots/documents.png)
Folder tree:
![Folder tree](docs/screenshots/folders.png)
## Features
- Write documentation directly in NetBox, displayed as safely sanitised rich text
- Word-like WYSIWYG editor with fonts, font sizes, colours, alignment and tables
- Hierarchical folders and sub-folders for a BookStack-like structure
- Wide editor view and TinyMCE full-screen mode
- Optionally assign documents and folders to tenants and tenant groups
- Upload images from your own device directly into a document
- Paste formatted Word content including tables and supported clipboard images
- Export and re-import multiple documents with folders, assignments and attachments as ZIP
- Print-optimised A4 view for printing or saving as PDF
- Full-page view via button or by clicking a table
- Readable tables with full cell borders and horizontal content scrolling
- Table presets, coloured header rows and cell highlighting in the editor
- Excel multi-sheet import: one document per worksheet in a chosen target folder
- Two-step Excel preview with sheet selection and editable document titles
- Optional flattening of Excel tables into compact field/value text blocks
- Assign one document to many objects and vice versa (unlimited; only identical duplicates are prevented)
- Supported objects: region, site, location, rack, device, VM, VM cluster and tenant/customer
- Import DOCX, XLSX/XLSM, text-based PDF, Markdown and text files
- Optionally keep the original file together with the document
- Find documents via NetBox global search and the REST API
- NetBox permissions, changelog, tags and custom fields
## Compatibility
- NetBox `4.4.0` – `4.7.x` (tested with 4.7.3)
- Python `>=3.10`
Test the plugin against your exact NetBox minor version in a staging instance
before a production rollout.
## Installation
### Installation aus dem Git-Repository
All paths assume a standard installation under `/opt/netbox`.
Das Plugin kann ohne vorheriges Klonen direkt aus dem Git-Repository in das Python-Virtualenv von NetBox installiert werden:
### 1. Install the package
```bash
source /opt/netbox/venv/bin/activate
pip install git+https://git.mrblake.cc/MrBlake/Netbox-DokiWiki.git@main
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/Netbox-Documentation.git@main"
```
### In `local_requirements.txt` eintragen
For reproducible production installs, replace `main` with a release tag or a
full commit ID.
Damit das Plugin bei NetBox-Updates und einer erneuten Installation der Python-Abhängigkeiten automatisch installiert wird, folgende Zeile in `/opt/netbox/local_requirements.txt` eintragen:
### 2. Add the plugin to `local_requirements.txt`
```text
git+https://git.mrblake.cc/MrBlake/Netbox-DokiWiki.git@main
```
Falls die Datei noch nicht existiert, kann sie erstellt werden:
This makes `upgrade.sh` reinstall the plugin automatically on every NetBox upgrade:
```bash
echo 'git+https://git.mrblake.cc/MrBlake/Netbox-DokiWiki.git@main' | sudo tee -a /opt/netbox/local_requirements.txt
grep -qxF "git+https://git.mrblake.cc/MrBlake/Netbox-Documentation.git@main" /opt/netbox/local_requirements.txt \
|| echo "git+https://git.mrblake.cc/MrBlake/Netbox-Documentation.git@main" | sudo tee -a /opt/netbox/local_requirements.txt
```
Danach die lokalen Abhängigkeiten installieren:
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`.
```bash
source /opt/netbox/venv/bin/activate
pip install -r /opt/netbox/local_requirements.txt
```
### 3. Enable the plugin
Bei einem privaten Repository muss der NetBox-Server Zugriff auf das Repository besitzen. Zugangsdaten sollten nicht direkt in `local_requirements.txt` gespeichert werden; stattdessen sollte ein geeigneter Git-Credential-Helper oder ein nur lesbarer Deployment-Zugang verwendet werden.
### NetBox konfigurieren
In `configuration.py`:
In `/opt/netbox/netbox/netbox/configuration.py`:
```python
PLUGINS = [
@@ -88,86 +106,178 @@ PLUGINS_CONFIG = {
"virtualization.cluster",
"tenancy.tenant",
],
}
},
}
```
TinyMCE wird als Python-Abhängigkeit des Plugins installiert und über einen lokalen, gecachten Plugin-Endpunkt bereitgestellt. `collectstatic` übernimmt die Dateien zusätzlich in NetBox. Der Editor benötigt deshalb weder Zugriff auf ein CDN noch einen API-Key. Das verwendete TinyMCE wird im GPL-Modus betrieben. Kann das Script nicht geladen werden, bleibt als Rückfall ein normales HTML-Textfeld verfügbar.
If other plugins are already configured, add `netbox_documentation` to the
existing list and dictionary instead of replacing them.
Danach die Migrationen und statischen Dateien aktualisieren und NetBox neu starten:
### 4. Apply migrations, collect static files, restart
```bash
cd /opt/netbox/netbox
python manage.py migrate
python manage.py collectstatic --no-input
/opt/netbox/venv/bin/python manage.py migrate netbox_documentation
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
Für Docker-Installationen das Paket in das NetBox-Image aufnehmen, Plugin und Konfiguration setzen und anschließend das Image neu bauen. Die hochgeladenen Originaldateien liegen im konfigurierten NetBox-`MEDIA_ROOT`; dieses Verzeichnis muss persistent gespeichert und gesichert werden.
TinyMCE is installed as a Python dependency and served via a local, cached
plugin endpoint; `collectstatic` also copies the files into NetBox. The editor
therefore needs neither CDN access nor an API key (TinyMCE runs in GPL mode). If
the script cannot be loaded, a plain HTML text field is used as a fallback.
## Berechtigungen
For Docker installations, add the package to your NetBox image, set plugin and
configuration, and rebuild the image. Uploaded files live in NetBox's
`MEDIA_ROOT`, which must be persistent and backed up.
Die benötigten Rechte können in NetBox unter **Admin → Benutzer → Berechtigungen** vergeben werden:
## Update
```bash
/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \
"git+https://git.mrblake.cc/MrBlake/Netbox-Documentation.git@main"
cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate netbox_documentation
/opt/netbox/venv/bin/python manage.py collectstatic --no-input
sudo systemctl restart netbox netbox-rq
```
`--force-reinstall` makes pip pick up branch changes even if the package
version has not been bumped.
When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from
`local_requirements.txt` and runs migrations and `collectstatic`:
```bash
sudo /opt/netbox/upgrade.sh
sudo systemctl restart netbox netbox-rq
```
Check the installed version and migrations:
```bash
/opt/netbox/venv/bin/pip show netbox-documentation
cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py showmigrations netbox_documentation
```
> **Migrating from the old repository name:** earlier versions were installed
> from `Netbox-DokiWiki.git`. Replace that line in
> `/opt/netbox/local_requirements.txt` with the URL above.
## Uninstall
1. Remove `"netbox_documentation"` 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-documentation
sudo systemctl restart netbox netbox-rq
```
## Configuration
| Key | Default | Description |
|---|---|---|
| `max_import_size_mb` | `25` | Maximum size of a single imported file |
| `max_archive_size_mb` | `250` | Maximum size of a ZIP archive import |
| `keep_imported_file` | `True` | Keep the original file as an attachment |
| `allowed_object_types` | see above | Object types documents can be assigned to |
## Usage
### Permissions
Grant permissions under **Admin → Users → Permissions**:
- `netbox_documentation.view_document`
- `netbox_documentation.add_document`, `change_document`, `delete_document`
- `netbox_documentation.view_documentassignment` sowie die entsprechenden Änderungsrechte
- `netbox_documentation.import_document` für Office-/PDF-Importe
- `netbox_documentation.view_documentassignment` and the corresponding change permissions
- `netbox_documentation.import_document` for Office/PDF imports
Objektbezogene NetBox-Constraints sollten zusätzlich passend zu Mandanten und Verantwortungsbereichen gesetzt werden. Nicht veröffentlichte Dokumente sind als Redaktionsstatus gedacht; sie ersetzen keine Objektberechtigung.
Set object-level constraints matching your tenants and areas of responsibility.
Unpublished documents are an editorial status, not a replacement for object
permissions.
## Importverhalten
### Import behaviour
| Format | Übernahme |
| Format | Imported content |
|---|---|
| DOCX | Überschriften, Absätze, Listen, Links und einfache Tabellen nach Markdown |
| XLSX/XLSM | Jedes Tabellenblatt als eigene Markdown-Tabelle; Formelergebnisse nur, wenn Excel sie zuvor gespeichert hat |
| PDF | Extrahierbarer Text, nach Seiten gegliedert |
| MD/TXT | Direkte Übernahme (UTF-8) |
| DOCX | Headings, paragraphs, lists, links and simple tables |
| XLSX/XLSM | Each worksheet as its own table; formula results only if Excel saved them |
| PDF | Extractable text, split by page |
| MD/TXT | Taken over directly (UTF-8) |
Alte binäre `.doc`- und `.xls`-Dateien müssen vorher in `.docx` bzw. `.xlsx` konvertiert werden. Gescannte PDFs benötigen OCR, die in dieser Version bewusst noch nicht enthalten ist. Komplexe Word-/PDF-Layouts, eingebettete Bilder und Excel-Formatierungen können nicht verlustfrei nach Markdown übertragen werden.
Legacy binary `.doc` and `.xls` files must be converted to `.docx`/`.xlsx`
first. Scanned PDFs require OCR, which is not included yet. Complex Word/PDF
layouts, embedded images and Excel formatting cannot be converted losslessly.
Für große Excel-Dateien kann auf der Importseite **„Excel mit mehreren Arbeitsblättern – je Blatt eine Dokumentation“** aktiviert werden. Dazu ist ein Zielordner verpflichtend. Jedes nicht leere Arbeitsblatt wird als eigene Dokumentation mit dem Blattnamen als Titel angelegt und erhält eine eigene Kopie der Original-Exceldatei als Anhang. Normale eingebettete PNG-, JPEG-, GIF- und WebP-Bilder werden dem jeweiligen Dokument als Medienanhang hinzugefügt. Diagramme, SmartArt, Steuerelemente und extern verknüpfte Bilder können nicht zuverlässig übernommen werden.
For large Excel files, enable **"Excel with multiple worksheets — one document
per sheet"** on the import page (a target folder is required). Every non-empty
worksheet becomes its own document titled after the sheet, with its own copy of
the original Excel file attached. Embedded PNG, JPEG, GIF and WebP images are
added as media attachments; charts, SmartArt, controls and externally linked
images cannot be imported reliably.
Vor dem Anlegen erscheint eine Vorschauseite mit allen erkannten Arbeitsblättern. Dort können einzelne Blätter abgewählt, die zukünftigen Dokumenttitel geändert und die jeweils erzeugte Dokumentation aufgeklappt werden. Erst die abschließende Bestätigung schreibt Dokumentationen und Anhänge in die Datenbank. Nicht bestätigte Vorschauen sind an den Benutzer gebunden und werden nach 24 Stunden bereinigt.
A preview page lists all detected worksheets first. Sheets can be deselected,
titles changed and the resulting documents expanded. Only the final
confirmation writes documents and attachments to the database. Unconfirmed
previews are bound to the user and cleaned up after 24 hours.
Mit **„Excel-Tabellen glätten“** werden normale Zellen ohne künstliche Datensatz- oder Feldbezeichnungen in ihrer Lesereihenfolge übernommen. Zellen einer Excel-Zeile erscheinen als einzelne Textzeilen eines Absatzes; zwischen Excel-Zeilen wird ein Absatz eingefügt. Bereiche, die in Excel ausdrücklich über **Einfügen → Tabelle** als strukturierte Tabelle gekennzeichnet wurden, bleiben dagegen als Tabelle erhalten. Rein optisch mit Rahmen oder Farben formatierte Bereiche gelten nicht als Tabelle. Nicht geglättete Tabellen werden in der Dokumentansicht automatisch kompakt dargestellt und bei Bedarf innerhalb des Inhalts horizontal scrollbar, ohne das NetBox-Layout zu verbreitern.
**"Flatten Excel tables"** takes over normal cells in reading order without
artificial record or field labels: cells of one row become lines of a paragraph,
rows are separated by paragraphs. Ranges explicitly formatted as a table in
Excel (**Insert → Table**) stay tables. Non-flattened tables are shown compactly
and scroll horizontally inside the content without widening the NetBox layout.
## REST-API
### ZIP archive
Nach Aktivierung stehen die üblichen NetBox-Plugin-Endpunkte bereit:
Under **Documentation → ZIP Export & Import**, multiple folders can be added via
a search field and downloaded together, optionally including all sub-folders.
Documents found by overlapping folder selections are included only once. The
archive contains:
- document content and metadata
- full folder paths
- assignments to NetBox objects
- imported files and editor images
On import, choose whether documents with the same identifier are updated or
created as new copies. Assignments to missing or disallowed objects are skipped.
Embedded image URLs are rewritten to the newly stored attachments.
Archives are checked for safe paths, file count, file types, compression ratio
and total extracted size before import. The size limit is set with
`max_archive_size_mb`.
### REST API
- `/api/plugins/documentation/documents/`
- `/api/plugins/documentation/assignments/`
- `/api/plugins/documentation/folders/`
- `/api/plugins/documentation/attachments/`
## ZIP-Archiv
Unter **Dokumentation → ZIP Export & Import** können mehrere Ordner über ein Suchfeld hinzugefügt und gemeinsam heruntergeladen werden. Optional werden alle Unterordner rekursiv einbezogen. Dokumentationen, die durch überlappende Ordnerauswahlen mehrfach gefunden werden, landen nur einmal im Archiv. Das Archiv enthält:
- Dokumentinhalt und Metadaten
- vollständige Ordnerpfade
- Zuordnungen zu NetBox-Objekten
- importierte Dateien und Editor-Bilder
Beim Import kann gewählt werden, ob Dokumentationen mit derselben Kennung aktualisiert oder als neue Kopie angelegt werden. Zuordnungen zu nicht vorhandenen beziehungsweise nicht erlaubten NetBox-Objekten werden übersprungen. Eingebettete Bild-URLs werden auf die neu gespeicherten Anhänge umgeschrieben.
Archive werden vor dem Import auf sichere Pfade, Dateianzahl, Dateitypen, Kompressionsverhältnis und entpackte Gesamtgröße geprüft. Das Größenlimit wird mit `max_archive_size_mb` in `PLUGINS_CONFIG` festgelegt.
## Entwicklung und Tests
## Development and tests
```bash
pip install -e ".[test]"
pytest
```
Für vollständige UI-/API-Tests muss NetBox im selben Virtualenv verfügbar sein. Die reinen Importtests befinden sich unter `netbox_documentation/tests/`.
Full UI/API tests require NetBox in the same virtualenv. The pure import tests
are located in `tests/`. `tests/test_metadata.py` fails when the NetBox range
in this README diverges from `min_version`/`max_version` in the plugin config.
## Nächste sinnvolle Ausbaustufen
## Roadmap
- OCR für gescannte PDFs (z. B. Tesseract/OCRmyPDF als optionaler Worker)
- eingebettete DOCX-Bilder als NetBox-Medien übernehmen
- echte Dokumentrevisionen mit Vergleich und Freigabeprozess
- asynchroner Massenimport großer Excel-Bestände über NetBox-RQ
- Vorlagen und automatisch vererbte Dokumentation entlang Region → Standort → Gerät
- OCR for scanned PDFs (e.g. Tesseract/OCRmyPDF as an optional worker)
- Import embedded DOCX images as NetBox media
- Real document revisions with diff and approval workflow
- Asynchronous bulk import of large Excel datasets via NetBox RQ
- Templates and inherited documentation along region → site → device
## License
Apache License 2.0.
Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

+6 -4
View File
@@ -1,14 +1,16 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginConfig
class DocumentationConfig(PluginConfig):
name = "netbox_documentation"
verbose_name = "NetBox Dokumentation"
description = "Wiki und Office-Dokumentation direkt in NetBox"
version = "0.7.4"
verbose_name = _("NetBox Documentation")
description = _("Wiki and office documentation directly in NetBox")
version = "0.12.1"
author = "LKE"
base_url = "documentation"
min_version = "4.0.0"
min_version = "4.4.0" # netbox.object_actions
max_version = "4.7.99"
django_apps = ["tinymce"]
default_settings = {
"allowed_object_types": [
+2 -2
View File
@@ -8,7 +8,7 @@ class DocumentSerializer(NetBoxModelSerializer):
class Meta:
model = Document
fields = ("id", "url", "display", "title", "slug", "category", "summary", "body", "body_format", "is_published", "tags", "created", "last_updated")
fields = ("id", "url", "display", "title", "slug", "category", "tenant_group", "tenant", "summary", "body", "body_format", "is_published", "tags", "created", "last_updated")
class DocumentAssignmentSerializer(NetBoxModelSerializer):
@@ -24,7 +24,7 @@ class DocumentCategorySerializer(NetBoxModelSerializer):
class Meta:
model = DocumentCategory
fields = ("id", "url", "display", "name", "slug", "parent", "description", "tags", "created", "last_updated")
fields = ("id", "url", "display", "name", "slug", "parent", "tenant_group", "tenant", "description", "tags", "created", "last_updated")
class DocumentAttachmentSerializer(NetBoxModelSerializer):
+125 -19
View File
@@ -5,8 +5,11 @@ from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.text import slugify
from django.utils.translation import gettext as _
from tenancy.models import Tenant, TenantGroup
from .models import Document, DocumentAssignment, DocumentAttachment, DocumentCategory
@@ -20,6 +23,14 @@ class ArchiveFailure(ValueError):
pass
def _save_imported_object(instance, context, **save_kwargs):
try:
instance.save(**save_kwargs)
except ValidationError as exc:
messages = getattr(exc, "messages", None) or [str(exc)]
raise ArchiveFailure(f"{context}: {'; '.join(messages)}") from exc
def documents_for_categories(categories, include_subfolders=True, user=None):
"""Return distinct permitted documents contained in the selected category trees."""
category_ids = set(categories.values_list("pk", flat=True))
@@ -43,11 +54,25 @@ def _category_path(category):
return list(reversed(path))
def _category_tenancy_path(category):
path, seen = [], set()
while category and category.pk not in seen:
path.append({
"tenant": category.tenant.slug if category.tenant else None,
"tenant_group": category.tenant_group.slug if category.tenant_group else None,
})
seen.add(category.pk)
category = category.parent
return list(reversed(path))
def export_documents(documents):
stream = SpooledTemporaryFile(max_size=10 * 1024 * 1024, mode="w+b")
manifest = {"format": ARCHIVE_FORMAT, "version": ARCHIVE_VERSION, "documents": []}
with ZipFile(stream, "w", compression=ZIP_DEFLATED, compresslevel=6) as archive:
for document in documents.prefetch_related("assignments__assigned_object_type", "attachments").select_related("category"):
for document in documents.prefetch_related("assignments__assigned_object_type", "attachments").select_related(
"category", "tenant", "tenant_group", "category__tenant", "category__tenant_group",
):
root = f"documents/{document.pk}"
extension = "html" if document.body_format == "html" else "md"
body_path = f"{root}/content.{extension}"
@@ -76,6 +101,9 @@ def export_documents(documents):
"title": document.title, "slug": document.slug, "summary": document.summary,
"body_format": document.body_format, "is_published": document.is_published,
"category_path": _category_path(document.category), "body_path": body_path,
"category_tenancy": _category_tenancy_path(document.category),
"tenant": document.tenant.slug if document.tenant else None,
"tenant_group": document.tenant_group.slug if document.tenant_group else None,
"assignments": assignments, "attachments": attachments,
})
archive.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"))
@@ -86,35 +114,103 @@ def export_documents(documents):
def _validate_archive(archive):
infos = archive.infolist()
if len(infos) > MAX_ENTRIES:
raise ArchiveFailure(f"Das Archiv enthält mehr als {MAX_ENTRIES} Dateien.")
raise ArchiveFailure(_("The archive contains more than %(count)s files.") % {"count": MAX_ENTRIES})
limit = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("max_archive_size_mb", 250) * 1024 * 1024
if sum(info.file_size for info in infos) > limit:
raise ArchiveFailure("Die entpackte Gesamtgröße überschreitet das konfigurierte Limit.")
raise ArchiveFailure(_("The total extracted size exceeds the configured limit."))
for info in infos:
path = PurePosixPath(info.filename)
if path.is_absolute() or ".." in path.parts:
raise ArchiveFailure("Das Archiv enthält einen unsicheren Dateipfad.")
raise ArchiveFailure(_("The archive contains an unsafe file path."))
if info.compress_size and info.file_size / info.compress_size > 200:
raise ArchiveFailure("Das Archiv enthält eine verdächtig stark komprimierte Datei.")
raise ArchiveFailure(_("The archive contains a suspiciously highly compressed file."))
def _read_json(archive, name):
try:
return json.loads(archive.read(name).decode("utf-8"))
except (KeyError, UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ArchiveFailure("Das Archiv enthält kein gültiges manifest.json.") from exc
raise ArchiveFailure(_("The archive contains no valid manifest.json.")) from exc
def _category_from_path(names):
def _resolve_tenant_group(slug, context):
"""Look up a tenant group by slug for an imported record.
Returns None if no slug was recorded (i.e. the object genuinely had no
tenant group). Raises ArchiveFailure if a slug *was* recorded but no
matching TenantGroup exists on this instance, instead of silently
dropping the assignment - a missing tenant group later tripping over
an unrelated validation rule further downstream is far more confusing
than failing here with a precise message.
"""
if not slug:
return None
group = TenantGroup.objects.filter(slug=slug).first()
if group is None:
raise ArchiveFailure(
_(
"%(context)s: The tenant group “%(slug)s” does not exist on this instance. "
"Create the tenant group first or repeat the import with an adjusted manifest.json."
) % {"context": context, "slug": slug}
)
return group
def _resolve_tenant(slug, context):
"""Look up a tenant by slug for an imported record.
Same reasoning as _resolve_tenant_group(): fail loudly and specifically
instead of leaving the field empty and letting a generic "a tenant is
required" validation error surface later with no indication of which
tenant or which record was actually the problem.
"""
if not slug:
return None
tenant = Tenant.objects.filter(slug=slug).first()
if tenant is None:
raise ArchiveFailure(
_(
"%(context)s: The tenant “%(slug)s” does not exist on this instance. "
"Create the tenant first or repeat the import with an adjusted manifest.json."
) % {"context": context, "slug": slug}
)
return tenant
def _category_from_path(names, tenancy_path=None):
parent = None
for name in names:
tenancy_path = tenancy_path or []
for index, name in enumerate(names):
name = str(name).strip()[:100]
if not name:
continue
slug = slugify(name)[:100] or "ordner"
slug = slugify(name)[:100] or "folder"
tenancy = tenancy_path[index] if index < len(tenancy_path) and isinstance(tenancy_path[index], dict) else {}
context = _("Folder “%(name)s”") % {"name": name}
tenant_group = _resolve_tenant_group(tenancy.get("tenant_group"), context)
tenant = _resolve_tenant(tenancy.get("tenant"), context)
if tenant and tenant_group and tenant.group_id != tenant_group.pk:
raise ArchiveFailure(
_("%(context)s: The tenant “%(tenant)s” does not belong to the tenant group “%(group)s” on this instance.")
% {"context": context, "tenant": tenant.slug, "group": tenant_group.slug}
)
category = DocumentCategory.objects.filter(parent=parent, slug=slug).first()
if not category:
category = DocumentCategory.objects.create(name=name, slug=slug, parent=parent)
# Set tenancy before the first save. NetBox installations may
# enforce a tenant via custom validation rules, so creating the
# category first and assigning its tenant in a second save fails.
category = DocumentCategory(
name=name, slug=slug, parent=parent,
tenant_group=tenant_group, tenant=tenant,
)
_save_imported_object(category, context)
elif tenancy:
category.tenant_group = tenant_group
category.tenant = tenant
_save_imported_object(
category, context,
update_fields=("tenant_group", "tenant", "last_updated"),
)
parent = category
return parent
@@ -133,27 +229,29 @@ def import_archive(upload, update_existing=False):
try:
archive = ZipFile(upload)
except BadZipFile as exc:
raise ArchiveFailure("Die hochgeladene Datei ist kein gültiges ZIP-Archiv.") from exc
raise ArchiveFailure(_("The uploaded file is not a valid ZIP archive.")) from exc
with archive:
_validate_archive(archive)
manifest = _read_json(archive, "manifest.json")
if manifest.get("format") != ARCHIVE_FORMAT or manifest.get("version") != ARCHIVE_VERSION:
raise ArchiveFailure("Archivformat oder Version wird nicht unterstützt.")
raise ArchiveFailure(_("Archive format or version is not supported."))
records = manifest.get("documents")
if not isinstance(records, list):
raise ArchiveFailure("Die Dokumentliste im Archiv ist ungültig.")
raise ArchiveFailure(_("The document list in the archive is invalid."))
allowed = set(settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("allowed_object_types", []))
created, updated, skipped_assignments = 0, 0, 0
for record in records:
if not isinstance(record, dict) or not record.get("title") or not record.get("body_path"):
raise ArchiveFailure("Das Archiv enthält einen unvollständigen Dokumenteintrag.")
raise ArchiveFailure(_("The archive contains an incomplete document entry."))
try:
body = archive.read(record["body_path"]).decode("utf-8")
except (KeyError, UnicodeDecodeError) as exc:
raise ArchiveFailure("Ein Dokumentinhalt fehlt oder ist nicht UTF-8-kodiert.") from exc
raise ArchiveFailure(_("A document body is missing or not UTF-8 encoded.")) from exc
source_slug = str(record.get("slug") or record["title"])
document = Document.objects.filter(slug=source_slug).first() if update_existing else None
category = _category_from_path(record.get("category_path") or [])
category = _category_from_path(
record.get("category_path") or [], record.get("category_tenancy") or [],
)
if document:
updated += 1
else:
@@ -165,7 +263,15 @@ def import_archive(upload, update_existing=False):
document.body_format = record.get("body_format") if record.get("body_format") in {"html", "markdown"} else "html"
document.is_published = bool(record.get("is_published", True))
document.category = category
document.save()
context = _("Document “%(title)s”") % {"title": document.title}
document.tenant_group = _resolve_tenant_group(record.get("tenant_group"), context)
document.tenant = _resolve_tenant(record.get("tenant"), context)
if document.tenant and document.tenant_group and document.tenant.group_id != document.tenant_group_id:
raise ArchiveFailure(
_("%(context)s: The tenant “%(tenant)s” does not belong to the tenant group “%(group)s” on this instance.")
% {"context": context, "tenant": document.tenant.slug, "group": document.tenant_group.slug}
)
_save_imported_object(document, context)
for assignment in record.get("assignments") or []:
label = f"{assignment.get('app_label')}.{assignment.get('model')}"
if label not in allowed:
@@ -188,12 +294,12 @@ def import_archive(upload, update_existing=False):
try:
content = archive.read(member)
except KeyError as exc:
raise ArchiveFailure(f"Anhang {member} fehlt im Archiv.") from exc
raise ArchiveFailure(_("Attachment %(name)s is missing from the archive.") % {"name": member}) from exc
from django.core.files.base import ContentFile
original_name = Path(str(item.get("original_name") or "attachment")).name[:255]
allowed_extensions = {".docx", ".xlsx", ".xlsm", ".pdf", ".md", ".txt", ".jpg", ".jpeg", ".png", ".gif", ".webp"}
if Path(original_name).suffix.lower() not in allowed_extensions:
raise ArchiveFailure(f"Der Anhang {original_name} verwendet einen nicht erlaubten Dateityp.")
raise ArchiveFailure(_("The attachment %(name)s uses a file type that is not allowed.") % {"name": original_name})
existing = document.attachments.filter(original_name=original_name, size=len(content)).first()
if existing:
if item.get("source_url"):
+55
View File
@@ -0,0 +1,55 @@
import base64
from io import BytesIO
import re
from django.utils.translation import gettext as _
class EmbeddedImageError(ValueError):
pass
DATA_IMAGE_RE = re.compile(
r"(?P<prefix>src\s*=\s*(?P<quote>['\"]))"
r"data:(?P<mime>image/(?:png|jpeg|gif|webp));base64,(?P<data>[^'\"]+)"
r"(?P=quote)",
re.IGNORECASE,
)
def _decode(match):
payload = re.sub(r"\s+", "", match.group("data"))
try:
content = base64.b64decode(payload, validate=True)
except (ValueError, TypeError) as exc:
raise EmbeddedImageError(_("A pasted image contains invalid Base64 data.")) from exc
try:
from PIL import Image
image = Image.open(BytesIO(content))
image.verify()
except Exception as exc:
raise EmbeddedImageError(_("Pasted content is not a valid image file.")) from exc
return match.group("mime").lower(), content
def validate_embedded_images(html, max_total_bytes):
total = 0
for match in DATA_IMAGE_RE.finditer(html or ""):
_mime, content = _decode(match)
total += len(content)
if total > max_total_bytes:
raise EmbeddedImageError(_("The pasted images exceed the allowed total size."))
def store_embedded_images(html, max_total_bytes, store):
total = 0
def replace(match):
nonlocal total
mime, content = _decode(match)
total += len(content)
if total > max_total_bytes:
raise EmbeddedImageError(_("The pasted images exceed the allowed total size."))
url = store(mime, content)
return f'{match.group("prefix")}{url}{match.group("quote")}'
return DATA_IMAGE_RE.sub(replace, html or "")
+2 -2
View File
@@ -5,7 +5,7 @@ from .models import Document, DocumentAssignment, DocumentCategory
class DocumentFilterSet(NetBoxModelFilterSet):
class Meta:
model = Document
fields = ("id", "title", "slug", "category_id", "is_published")
fields = ("id", "title", "slug", "category_id", "tenant_group_id", "tenant_id", "is_published")
def search(self, queryset, name, value):
from django.db.models import Q
@@ -21,7 +21,7 @@ class AssignmentFilterSet(NetBoxModelFilterSet):
class DocumentCategoryFilterSet(NetBoxModelFilterSet):
class Meta:
model = DocumentCategory
fields = ("id", "name", "slug", "parent_id")
fields = ("id", "name", "slug", "parent_id", "tenant_group_id", "tenant_id")
def search(self, queryset, name, value):
return queryset.filter(name__icontains=value)
+117 -42
View File
@@ -1,8 +1,12 @@
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.files.base import ContentFile
from django.db.models import Q
from django.utils.functional import lazy
from django.utils.html import format_html
from django.utils.safestring import SafeString
from django.utils.translation import gettext_lazy as _
from utilities.forms import get_field_value
from utilities.forms.fields import (
ContentTypeChoiceField, DynamicModelChoiceField, DynamicModelMultipleChoiceField, SlugField,
@@ -11,10 +15,12 @@ from utilities.forms.rendering import FieldSet
from utilities.forms.widgets import HTMXSelect
from netbox.forms import NetBoxModelForm
from dcim.models import Device
from .models import Document, DocumentAssignment, DocumentCategory
from tenancy.models import Tenant, TenantGroup
from .embedded_images import EmbeddedImageError, store_embedded_images, validate_embedded_images
from .models import Document, DocumentAssignment, DocumentAttachment, DocumentCategory
def help_label(label, description):
def _help_label(label, description):
return format_html(
'{} <span class="mdi mdi-help-circle-outline text-muted" title="{}" '
'data-bs-toggle="tooltip" aria-label="{}"></span>',
@@ -22,6 +28,9 @@ def help_label(label, description):
)
help_label = lazy(_help_label, SafeString) # labels are built at import time, render in the request language
def allowed_content_types():
labels = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get(
"allowed_object_types", []
@@ -35,20 +44,27 @@ def allowed_content_types():
class DocumentForm(NetBoxModelForm):
slug = SlugField(slug_source="title")
body = forms.CharField(required=False, label="Inhalt", widget=forms.Textarea(attrs={
body = forms.CharField(required=False, label=_("Content"), widget=forms.Textarea(attrs={
"rows": 32, "class": "rich-text-editor", "data-rich-text-editor": "true"
}), help_text="Formatierter Text mit Tabellen, Farben, Schriftarten und Größen.")
}), help_text=_("Formatted text with tables, colours, fonts and sizes."))
body_format = forms.CharField(widget=forms.HiddenInput(), initial="html")
category = DynamicModelChoiceField(queryset=DocumentCategory.objects.all(), required=False, label="Ordner")
category = DynamicModelChoiceField(queryset=DocumentCategory.objects.all(), required=False, label=_("Folder"))
tenant_group = DynamicModelChoiceField(
queryset=TenantGroup.objects.all(), required=False, selector=True, label=_("Tenant group"),
)
tenant = DynamicModelChoiceField(
queryset=Tenant.objects.all(), required=False, selector=True, label=_("Tenant"),
query_params={"group_id": "$tenant_group"},
)
fieldsets = (
FieldSet("title", "slug", "category", "summary", "is_published", "tags", name="Dokumentation"),
FieldSet("body", "body_format", name="Inhalt"),
FieldSet("title", "slug", "category", "tenant_group", "tenant", "summary", "is_published", "tags", name=_("Document")),
FieldSet("body", "body_format", name=_("Content")),
)
class Meta:
model = Document
fields = ("title", "slug", "category", "summary", "body", "body_format", "is_published", "tags")
fields = ("title", "slug", "category", "tenant_group", "tenant", "summary", "body", "body_format", "is_published", "tags")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -59,14 +75,55 @@ class DocumentForm(NetBoxModelForm):
self.initial["body"] = markdown(self.instance.body, extensions=("extra", "sane_lists"))
self.initial["body_format"] = "html"
def clean_body(self):
body = self.cleaned_data.get("body", "")
limit = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("max_import_size_mb", 25)
try:
validate_embedded_images(body, limit * 1024 * 1024)
except EmbeddedImageError as exc:
raise forms.ValidationError(str(exc)) from exc
return body
def clean(self):
super().clean()
cleaned = self.cleaned_data
tenant, group = cleaned.get("tenant"), cleaned.get("tenant_group")
if tenant and group and tenant.group_id != group.pk:
self.add_error("tenant", _("The tenant does not belong to the selected tenant group."))
return cleaned
def save(self, commit=True):
document = super().save(commit=commit)
if not commit or not document.pk or "data:image/" not in (document.body or "").lower():
return document
limit = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("max_import_size_mb", 25)
counter = 0
def save_image(mime, content):
nonlocal counter
counter += 1
extension = {"image/jpeg": "jpg", "image/png": "png", "image/gif": "gif", "image/webp": "webp"}[mime]
name = f"editor-image-{document.pk}-{counter}.{extension}"
attachment = DocumentAttachment(
document=document, original_name=name, content_type=mime, size=len(content),
)
attachment.file.save(name, ContentFile(content), save=False)
attachment.save()
return attachment.file.url
document.body = store_embedded_images(document.body, limit * 1024 * 1024, save_image)
document.save(update_fields=("body", "last_updated"))
return document
class AssignmentForm(NetBoxModelForm):
assigned_object_type = ContentTypeChoiceField(queryset=ContentType.objects.none(), label="Objekttyp", widget=HTMXSelect())
assigned_object_type = ContentTypeChoiceField(queryset=ContentType.objects.none(), label=_("Object type"), widget=HTMXSelect())
assigned_object = DynamicModelChoiceField(
queryset=Device.objects.none(), label="NetBox-Objekt", required=True, disabled=True, selector=True
queryset=Device.objects.none(), label=_("NetBox object"), required=True, disabled=True, selector=True
)
fieldsets = (FieldSet("document", "assigned_object_type", "assigned_object", "note", "tags", name="Dokumentation zuordnen"),)
fieldsets = (FieldSet("document", "assigned_object_type", "assigned_object", "note", "tags", name=_("Assign document")),)
class Meta:
model = DocumentAssignment
@@ -98,48 +155,63 @@ class AssignmentForm(NetBoxModelForm):
class DocumentCategoryForm(NetBoxModelForm):
slug = SlugField(slug_source="name")
parent = DynamicModelChoiceField(queryset=DocumentCategory.objects.all(), required=False, label="Übergeordneter Ordner")
parent = DynamicModelChoiceField(queryset=DocumentCategory.objects.all(), required=False, label=_("Parent folder"))
tenant_group = DynamicModelChoiceField(
queryset=TenantGroup.objects.all(), required=False, selector=True, label=_("Tenant group"),
)
tenant = DynamicModelChoiceField(
queryset=Tenant.objects.all(), required=False, selector=True, label=_("Tenant"),
query_params={"group_id": "$tenant_group"},
)
fieldsets = (FieldSet("name", "slug", "parent", "description", "tags", name="Ordner"),)
fieldsets = (FieldSet("name", "slug", "parent", "tenant_group", "tenant", "description", "tags", name=_("Folder")),)
class Meta:
model = DocumentCategory
fields = ("name", "slug", "parent", "description", "tags")
fields = ("name", "slug", "parent", "tenant_group", "tenant", "description", "tags")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
self.fields["parent"].queryset = DocumentCategory.objects.exclude(pk=self.instance.pk)
def clean(self):
super().clean()
cleaned = self.cleaned_data
tenant, group = cleaned.get("tenant"), cleaned.get("tenant_group")
if tenant and group and tenant.group_id != group.pk:
self.add_error("tenant", _("The tenant does not belong to the selected tenant group."))
return cleaned
class ImportForm(forms.Form):
file = forms.FileField(label="Word-, Excel- oder PDF-Datei")
file = forms.FileField(label=_("Word, Excel or PDF file"))
title = forms.CharField(max_length=200, required=False, label=help_label(
"Titel", "Leer lassen, um den Dateinamen als Titel zu verwenden. Beim Mehrblattimport werden die Blattnamen verwendet."
_("Title"), _("Leave empty to use the file name as title. Multi-sheet imports use the sheet names.")
))
append = forms.BooleanField(required=False, initial=False, label=help_label(
"An bestehende Dokumentation anhängen", "Fügt den importierten Inhalt am Ende einer vorhandenen Dokumentation an."
_("Append to existing document"), _("Adds the imported content to the end of an existing document.")
))
document = forms.ModelChoiceField(queryset=Document.objects.all(), required=False, label=help_label(
"Bestehende Dokumentation", "Zieldokumentation für die Funktion Anhängen."
_("Existing document"), _("Target document for appending.")
))
excel_sheets_as_documents = forms.BooleanField(
required=False,
label=help_label(
"Excel mit mehreren Arbeitsblättern – je Blatt eine Dokumentation",
"Erstellt aus jedem nicht leeren Excel-Arbeitsblatt eine eigene Dokumentation im gewählten Zielordner.",
_("Excel with multiple worksheets – one document per sheet"),
_("Creates a separate document in the selected target folder from every non-empty Excel worksheet."),
),
)
flatten_excel_tables = forms.BooleanField(
required=False,
label=help_label(
"Excel-Tabellen glätten",
"Übernimmt normale Zellen ohne Tabelle als dokumentartigen Text. Nur in Excel ausdrücklich über Einfügen → Tabelle definierte Bereiche bleiben Tabellen.",
_("Flatten Excel tables"),
_("Imports plain cells outside tables as document-style text. Only ranges explicitly defined in Excel via Insert → Table remain tables."),
),
)
category = forms.ModelChoiceField(
queryset=DocumentCategory.objects.none(), required=False,
label=help_label("Zielordner / Kategorie", "Für den Excel-Mehrblattimport verpflichtend."),
label=help_label(_("Target folder / category"), _("Required for the Excel multi-sheet import.")),
)
def __init__(self, *args, user=None, **kwargs):
@@ -151,30 +223,30 @@ class ImportForm(forms.Form):
def clean(self):
data = super().clean()
if data.get("append") and not data.get("document"):
self.add_error("document", "Zum Anhängen muss eine Dokumentation gewählt werden.")
self.add_error("document", _("Select a document to append to."))
upload = data.get("file")
if data.get("excel_sheets_as_documents"):
if upload and not upload.name.lower().endswith((".xlsx", ".xlsm")):
self.add_error("file", "Der Mehrblattimport benötigt eine XLSX- oder XLSM-Datei.")
self.add_error("file", _("The multi-sheet import requires an XLSX or XLSM file."))
if not data.get("category"):
self.add_error("category", "Bitte einen Zielordner für die erzeugten Dokumentationen auswählen.")
self.add_error("category", _("Select a target folder for the generated documents."))
if data.get("append"):
self.add_error("append", "Mehrblattimport und Anhängen können nicht kombiniert werden.")
self.add_error("append", _("Multi-sheet import and appending cannot be combined."))
limit = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("max_import_size_mb", 25)
if upload and upload.size > limit * 1024 * 1024:
self.add_error("file", f"Die Datei ist größer als {limit} MB.")
self.add_error("file", _("The file is larger than %(limit)s MB.") % {"limit": limit})
return data
class ArchiveExportForm(forms.Form):
categories = DynamicModelMultipleChoiceField(
queryset=DocumentCategory.objects.all(), selector=True,
label="Ordner und Kategorien",
help_text="Einen oder mehrere Ordner suchen und hinzufügen.",
label=_("Folders and categories"),
help_text=_("Search for and add one or more folders."),
)
include_subfolders = forms.BooleanField(
required=False, initial=True, label="Unterordner einbeziehen",
help_text="Exportiert Dokumentationen aus allen untergeordneten Ordnern.",
required=False, initial=True, label=_("Include subfolders"),
help_text=_("Exports documents from all subfolders."),
)
def __init__(self, *args, user=None, **kwargs):
@@ -186,38 +258,38 @@ class ArchiveExportForm(forms.Form):
class ArchiveImportForm(forms.Form):
archive = forms.FileField(label="ZIP-Archiv")
archive = forms.FileField(label=_("ZIP archive"))
update_existing = forms.BooleanField(
required=False, initial=False,
label="Bestehende Dokumentationen mit gleicher Kennung aktualisieren",
help_text="Ohne diese Option werden bei Namenskonflikten neue Dokumentationen mit einer fortlaufenden Kennung angelegt.",
label=_("Update existing documents with the same slug"),
help_text=_("Without this option, name conflicts create new documents with a numbered slug."),
)
def clean_archive(self):
upload = self.cleaned_data["archive"]
if not upload.name.lower().endswith(".zip"):
raise forms.ValidationError("Bitte ein vom Plugin erzeugtes ZIP-Archiv auswählen.")
raise forms.ValidationError(_("Select a ZIP archive created by this plugin."))
limit = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("max_archive_size_mb", 250)
if upload.size > limit * 1024 * 1024:
raise forms.ValidationError(f"Das Archiv ist größer als {limit} MB.")
raise forms.ValidationError(_("The archive is larger than %(limit)s MB.") % {"limit": limit})
return upload
class ExcelSheetSelectionForm(forms.Form):
include = forms.BooleanField(
required=False, initial=True, label="Importieren",
required=False, initial=True, label=_("Import"),
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
)
index = forms.IntegerField(widget=forms.HiddenInput())
title = forms.CharField(
max_length=200, required=False, label="Dokumenttitel",
max_length=200, required=False, label=_("Document title"),
widget=forms.TextInput(attrs={"class": "form-control"}),
)
def clean(self):
data = super().clean()
if data.get("include") and not (data.get("title") or "").strip():
self.add_error("title", "Für ein ausgewähltes Arbeitsblatt ist ein Titel erforderlich.")
self.add_error("title", _("A selected worksheet requires a title."))
return data
@@ -228,10 +300,13 @@ class BaseExcelSheetSelectionFormSet(forms.BaseFormSet):
return
selected = [form.cleaned_data for form in self.forms if form.cleaned_data.get("include")]
if not selected:
raise forms.ValidationError("Bitte mindestens ein Arbeitsblatt auswählen.")
raise forms.ValidationError(_("Select at least one worksheet."))
indices = [item["index"] for item in selected]
if len(indices) != len(set(indices)):
raise forms.ValidationError("Die Arbeitsblattauswahl ist ungültig.")
raise forms.ValidationError(_("The worksheet selection is invalid."))
titles = [item["title"].strip().casefold() for item in selected]
if len(titles) != len(set(titles)):
raise forms.ValidationError(_("Selected worksheets must not have the same document title."))
ExcelSheetSelectionFormSet = forms.formset_factory(
+57
View File
@@ -0,0 +1,57 @@
"""Server-side syntax highlighting of code blocks in rendered documents (VS Code-like colours).
Runs on already sanitised HTML: the code text is unescaped, re-tokenised by Pygments and
re-escaped, so only Pygments' own <span class="..."> markup is added.
"""
import html
import re
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.util import ClassNotFound
_PRE = re.compile(r"<pre(?P<attrs>[^>]*)>(?:<code(?P<code_attrs>[^>]*)>)?(?P<body>.*?)(?:</code>)?</pre>", re.S)
_LANGUAGE = re.compile(r'class="[^"]*\b(?:lang|language)-(?P<name>[\w+#.-]+)')
_BR = re.compile(r"<br\s*/?>", re.I)
_TAG = re.compile(r"<[^>]+>")
# Language names used by TinyMCE's code sample plugin and common Markdown fences.
_ALIASES = {
"markup": "html", "shell": "bash", "sh": "bash", "ps": "powershell", "ps1": "powershell",
"yml": "yaml", "js": "javascript", "ts": "typescript", "py": "python",
}
_PLAIN = {"none", "plaintext", "text", "plain", "txt"}
_FORMATTER = HtmlFormatter(nowrap=True)
def _lexer(name, code):
if name:
name = _ALIASES.get(name.lower(), name.lower())
if name in _PLAIN:
return None
try:
return get_lexer_by_name(name)
except ClassNotFound:
return None
# No language given: only trust a confident guess, otherwise leave the block plain.
try:
lexer = guess_lexer(code)
except ClassNotFound:
return None
return lexer if lexer.analyse_text(code) >= 0.5 else None
def _replace(match):
language = _LANGUAGE.search((match.group("attrs") or "") + (match.group("code_attrs") or ""))
code = html.unescape(_TAG.sub("", _BR.sub("\n", match.group("body")))).rstrip("\n")
lexer = _lexer(language.group("name") if language else None, code)
if lexer is None:
return match.group(0)
highlighted = highlight(code, lexer, _FORMATTER).rstrip("\n")
label = html.escape(lexer.name, quote=True)
return f'<pre class="doc-hl" data-lang="{label}"><code>{highlighted}</code></pre>'
def highlight_code_blocks(value):
return _PRE.sub(_replace, value)
+253 -40
View File
@@ -1,8 +1,11 @@
from dataclasses import dataclass, field
from io import BytesIO
from pathlib import Path
from html import escape
import re
from django.utils.translation import gettext as _
class ImportFailure(ValueError):
pass
@@ -12,6 +15,7 @@ class ImportFailure(ValueError):
class ImportResult:
markdown: str
warnings: list[str] = field(default_factory=list)
body_format: str = "markdown"
@dataclass
@@ -27,6 +31,8 @@ class ExcelSheetResult:
title: str
markdown: str
images: list[ImportedImage] = field(default_factory=list)
body_format: str = "markdown"
source_index: int = 0
def import_document(upload, flatten_excel=False) -> ImportResult:
@@ -42,8 +48,8 @@ def import_document(upload, flatten_excel=False) -> ImportResult:
if suffix in {".md", ".txt"}:
return ImportResult(content.decode("utf-8-sig"))
if suffix in {".doc", ".xls"}:
raise ImportFailure("Alte .doc/.xls-Dateien bitte zuerst als .docx/.xlsx speichern.")
raise ImportFailure("Unterstützt werden DOCX, XLSX, XLSM, PDF, Markdown und Text.")
raise ImportFailure(_("Please save legacy .doc/.xls files as .docx/.xlsx first."))
raise ImportFailure(_("Supported formats are DOCX, XLSX, XLSM, PDF, Markdown and text."))
def _docx(content):
@@ -80,7 +86,7 @@ def _escape_markdown_text(value):
def _xlsx(content, flatten=False):
from openpyxl import load_workbook
workbook = load_workbook(BytesIO(content), read_only=not flatten, data_only=True)
workbook = load_workbook(BytesIO(content), read_only=False, data_only=True)
sections = []
for sheet in workbook.worksheets:
rows = [["" if cell is None else str(cell) for cell in row] for row in sheet.iter_rows(values_only=True)]
@@ -88,29 +94,31 @@ def _xlsx(content, flatten=False):
rows.pop()
if not rows:
continue
rendered = _render_flattened_worksheet(sheet) if flatten else _render_excel_rows(rows)
sections.append(f"## {sheet.title}\n\n{rendered}")
rendered = _render_flattened_worksheet(sheet, workbook) if flatten else _render_excel_worksheet_html(sheet, workbook)
sections.append(f"<h2>{escape(sheet.title)}</h2>\n{rendered}")
if not sections:
raise ImportFailure("Die Arbeitsmappe enthält keine Daten.")
return ImportResult("\n\n".join(sections))
raise ImportFailure(_("The workbook contains no data."))
return ImportResult("\n\n".join(sections), body_format="html")
def import_excel_sheets(upload, flatten=False) -> list[ExcelSheetResult]:
def import_excel_sheets(
upload, flatten=False, *, metadata_only=False, preview_max_rows=None,
include_image_data=True, selected_indexes=None,
) -> list[ExcelSheetResult]:
"""Convert each non-empty worksheet into an individual document payload."""
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
suffix = Path(upload.name).suffix.lower()
if suffix not in {".xlsx", ".xlsm"}:
raise ImportFailure("Der Mehrblattimport unterstützt XLSX- und XLSM-Dateien.")
content = upload.read()
raise ImportFailure(_("The multi-sheet import supports XLSX and XLSM files."))
upload.seek(0)
workbook = load_workbook(BytesIO(content), read_only=False, data_only=True)
workbook = load_workbook(upload, read_only=False, data_only=True)
results = []
for sheet in workbook.worksheets:
rows = [["" if cell is None else str(cell) for cell in row] for row in sheet.iter_rows(values_only=True)]
while rows and not any(value for value in rows[-1]):
rows.pop()
selected_indexes = set(selected_indexes) if selected_indexes is not None else None
for source_index, sheet in enumerate(workbook.worksheets):
if selected_indexes is not None and source_index not in selected_indexes:
continue
images = []
for number, image in enumerate(getattr(sheet, "_images", ()), 1):
image_format = (getattr(image, "format", None) or "png").lower()
@@ -121,32 +129,232 @@ def import_excel_sheets(upload, flatten=False) -> list[ExcelSheetResult]:
anchor = getattr(image, "anchor", None)
marker = getattr(anchor, "_from", None)
cell = f"{get_column_letter(marker.col + 1)}{marker.row + 1}" if marker else ""
try:
image_content = image._data()
except (AttributeError, OSError, ValueError):
continue
image_content = b""
if include_image_data and not metadata_only:
try:
image_content = image._data()
except (AttributeError, OSError, ValueError):
continue
images.append(ImportedImage(
name=f"{slugify_filename(sheet.title)}-{number}.{image_format if image_format != 'jpeg' else 'jpg'}",
content=image_content, content_type=f"image/{image_format}", cell=cell,
))
if not rows and not images:
has_content = _worksheet_has_content(sheet)
if not has_content and not images:
continue
if rows:
markdown = _render_flattened_worksheet(sheet) if flatten else _render_excel_rows(rows)
if metadata_only:
markdown = ""
elif has_content:
markdown = (
_render_flattened_worksheet(sheet, workbook, max_rows=preview_max_rows) if flatten else
_render_excel_worksheet_html(sheet, workbook, max_rows=preview_max_rows)
)
else:
markdown = ""
results.append(ExcelSheetResult(title=sheet.title, markdown=markdown, images=images))
results.append(ExcelSheetResult(
title=sheet.title, markdown=markdown, images=images,
body_format="html", source_index=source_index,
))
workbook.close()
upload.seek(0)
if not results:
raise ImportFailure("Die Arbeitsmappe enthält keine Daten oder unterstützten Bilder.")
raise ImportFailure(_("The workbook contains no data or supported images."))
return results
def _worksheet_has_content(sheet):
"""Check for a value without materializing the complete worksheet in memory."""
return any(
cell.value not in (None, "")
for row in sheet.iter_rows()
for cell in row
)
def slugify_filename(value):
value = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-.")
return value[:80] or "arbeitsblatt"
def _render_flattened_worksheet(sheet):
def _excel_color(color, workbook):
"""Resolve RGB, indexed and theme-based openpyxl colors to a CSS hex value."""
if not color or not getattr(color, "type", None):
return None
value = None
if color.type == "rgb" and color.rgb:
value = str(color.rgb)[-6:]
elif color.type == "indexed" and color.indexed is not None:
from openpyxl.styles.colors import COLOR_INDEX
index = int(color.indexed)
if 0 <= index < len(COLOR_INDEX):
value = COLOR_INDEX[index][-6:]
elif color.type == "theme" and color.theme is not None and workbook.loaded_theme:
from xml.etree import ElementTree
try:
root = ElementTree.fromstring(workbook.loaded_theme)
scheme = root.find(".//{http://schemas.openxmlformats.org/drawingml/2006/main}clrScheme")
entries = list(scheme) if scheme is not None else []
entry = entries[int(color.theme)]
color_node = next(iter(entry))
value = color_node.attrib.get("val") or color_node.attrib.get("lastClr")
except (ElementTree.ParseError, IndexError, StopIteration, TypeError, ValueError):
value = None
if not value or not re.fullmatch(r"[0-9A-Fa-f]{6}", value):
return None
rgb = [int(value[index:index + 2], 16) for index in (0, 2, 4)]
tint = float(getattr(color, "tint", 0) or 0)
if tint:
rgb = [round(component * (1 + tint) if tint < 0 else component + (255 - component) * tint) for component in rgb]
return "#" + "".join(f"{max(0, min(255, component)):02x}" for component in rgb)
def _excel_cell_style(cell, workbook):
declarations = []
if cell.fill and cell.fill.fill_type:
fill = (
_excel_color(getattr(cell.fill, "fgColor", None), workbook) or
_excel_color(getattr(cell.fill, "bgColor", None), workbook)
)
if not fill and cell.fill.fill_type == "linear":
stops = getattr(cell.fill, "stop", ())
fill = _excel_color(stops[0].color, workbook) if stops else None
if fill:
declarations.append(f"background-color: {fill}")
font_color = _excel_color(cell.font.color, workbook)
if font_color:
declarations.append(f"color: {font_color}")
if cell.font.bold:
declarations.append("font-weight: bold")
if cell.font.italic:
declarations.append("font-style: italic")
if cell.font.sz:
declarations.append(f"font-size: {float(cell.font.sz):g}pt")
if cell.alignment.horizontal in {"left", "center", "right", "justify"}:
declarations.append(f"text-align: {cell.alignment.horizontal}")
if cell.alignment.vertical in {"top", "center", "bottom"}:
declarations.append(f"vertical-align: {'middle' if cell.alignment.vertical == 'center' else cell.alignment.vertical}")
if cell.alignment.wrap_text:
declarations.append("white-space: normal")
return "; ".join(declarations)
def _tint_hex(value, tint):
import colorsys
rgb = tuple(int(value[index:index + 2], 16) / 255 for index in (1, 3, 5))
hue, lightness, saturation = colorsys.rgb_to_hls(*rgb)
lightness = lightness * (1 + tint) if tint < 0 else lightness + (1 - lightness) * tint
tinted = colorsys.hls_to_rgb(hue, max(0, min(1, lightness)), saturation)
return "#" + "".join(f"{round(component * 255):02x}" for component in tinted)
def _excel_table_cell_styles(sheet, workbook, max_row, max_column):
"""Create visual fallbacks for Excel's built-in 'Format as Table' styles."""
from openpyxl.styles import Color
from openpyxl.utils.cell import range_boundaries
styles = {}
for table in sheet.tables.values():
info = table.tableStyleInfo
match = re.fullmatch(r"TableStyle(Light|Medium|Dark)(\d+)", info.name or "") if info else None
if not match:
continue
family, number = match.group(1), int(match.group(2))
palette_slot = (number - 1) % 7
theme_index = 0 if palette_slot == 0 else 3 + palette_slot
base = _excel_color(Color(theme=theme_index), workbook) or "#4472c4"
min_col, min_row, table_max_col, table_max_row = range_boundaries(table.ref)
table_max_col, table_max_row = min(table_max_col, max_column), min(table_max_row, max_row)
if min_col > table_max_col or min_row > table_max_row:
continue
header_fill = _tint_hex(base, 0.55) if family == "Light" else base
header_color = "#000000" if family == "Light" else "#ffffff"
stripe_fill = _tint_hex(base, 0.88 if family == "Light" else 0.82)
for column in range(min_col, table_max_col + 1):
styles[(min_row, column)] = f"background-color: {header_fill}; color: {header_color}; font-weight: bold"
data_start = min_row + (1 if table.headerRowCount else 0)
data_end = table_max_row - (1 if table.totalsRowShown else 0)
if info.showRowStripes:
for row in range(data_start, data_end + 1):
if (row - data_start) % 2 == 1:
for column in range(min_col, table_max_col + 1):
styles[(row, column)] = f"background-color: {stripe_fill}"
if table.totalsRowShown and table_max_row >= min_row:
for column in range(min_col, table_max_col + 1):
styles[(table_max_row, column)] = f"font-weight: bold; border-top: 2px solid {base}"
return styles
def _render_excel_worksheet_html(sheet, workbook, max_rows=None, bounds=None):
"""Render worksheet values and the most relevant visual Excel cell formatting."""
from openpyxl.utils import get_column_letter
if bounds:
start_column, start_row, bound_max_column, bound_max_row = bounds
else:
start_column, start_row, bound_max_column, bound_max_row = 1, 1, sheet.max_column, sheet.max_row
last_row = last_column = 0
for row in sheet.iter_rows(
min_row=start_row, max_row=bound_max_row,
min_col=start_column, max_col=bound_max_column,
):
for cell in row:
if cell.value not in (None, ""):
last_row = max(last_row, cell.row)
last_column = max(last_column, cell.column)
if not last_row:
return "<p><em>Keine Inhalte</em></p>"
max_row = min(last_row, start_row + max_rows - 1) if max_rows else last_row
max_column = last_column
table_styles = _excel_table_cell_styles(sheet, workbook, max_row, max_column)
merged_starts, merged_children = {}, set()
for merged in sheet.merged_cells.ranges:
if merged.min_row > max_row or merged.min_col > max_column:
continue
merged_starts[(merged.min_row, merged.min_col)] = (
min(merged.max_row, max_row) - merged.min_row + 1,
min(merged.max_col, max_column) - merged.min_col + 1,
)
for row in range(merged.min_row, min(merged.max_row, max_row) + 1):
for column in range(merged.min_col, min(merged.max_col, max_column) + 1):
if (row, column) != (merged.min_row, merged.min_col):
merged_children.add((row, column))
columns = []
for column in range(start_column, max_column + 1):
width = sheet.column_dimensions[get_column_letter(column)].width
columns.append(f'<col style="width: {max(3, min(float(width or 13), 80)):.2f}ch">')
output = ['<table class="doc-table-bordered"><colgroup>', *columns, "</colgroup><tbody>"]
for row in range(start_row, max_row + 1):
row_style = ""
if sheet.row_dimensions[row].height:
row_style = f' style="height: {float(sheet.row_dimensions[row].height):g}pt"'
output.append(f"<tr{row_style}>")
for column in range(start_column, max_column + 1):
if (row, column) in merged_children:
continue
cell = sheet.cell(row=row, column=column)
attributes = []
rowspan, colspan = merged_starts.get((row, column), (1, 1))
if rowspan > 1:
attributes.append(f'rowspan="{rowspan}"')
if colspan > 1:
attributes.append(f'colspan="{colspan}"')
style = _excel_cell_style(cell, workbook)
if not style and (row, column) in table_styles:
style = table_styles[(row, column)]
elif (row, column) in table_styles and "background-color" not in style:
style = "; ".join(filter(None, (style, table_styles[(row, column)])))
if style:
attributes.append(f'style="{style}"')
value = "" if cell.value is None else escape(str(cell.value)).replace("\n", "<br>")
output.append(f"<td{' ' if attributes else ''}{' '.join(attributes)}>{value}</td>")
output.append("</tr>")
output.append("</tbody></table>")
if max_rows and last_row > start_row + max_rows - 1:
output.append("<p><em>%s</em></p>" % escape(_("Preview limited to %(rows)s rows.") % {"rows": max_rows}))
return "".join(output)
def _render_flattened_worksheet(sheet, workbook, max_rows=None):
"""Flatten ordinary cells while preserving explicitly defined Excel tables."""
from openpyxl.utils.cell import range_boundaries
@@ -165,7 +373,8 @@ def _render_flattened_worksheet(sheet):
blocks = []
rendered_tables = set()
for row_number in range(1, sheet.max_row + 1):
rendered_max_row = min(sheet.max_row, max_rows) if max_rows else sheet.max_row
for row_number in range(1, rendered_max_row + 1):
ordinary_values = []
tables_starting_here = []
for column_number in range(1, sheet.max_column + 1):
@@ -175,20 +384,24 @@ def _render_flattened_worksheet(sheet):
tables_starting_here.append(bounds)
rendered_tables.add(bounds)
continue
value = sheet.cell(row=row_number, column=column_number).value
cell = sheet.cell(row=row_number, column=column_number)
value = cell.value
if value not in (None, ""):
ordinary_values.append(_escape_markdown_text(value))
rendered_value = escape(str(value)).replace("\n", "<br>")
style = _excel_cell_style(cell, workbook) if cell.has_style else ""
if style:
rendered_value = f'<span style="{style}">{rendered_value}</span>'
ordinary_values.append(rendered_value)
if ordinary_values:
blocks.append(" \n".join(ordinary_values))
blocks.append("<p>" + "<br>".join(ordinary_values) + "</p>")
for min_col, min_row, max_col, max_row in tables_starting_here:
rows = []
for table_row in sheet.iter_rows(
min_row=min_row, max_row=max_row, min_col=min_col, max_col=max_col, values_only=True
):
rows.append(["" if value is None else str(value) for value in table_row])
if rows:
blocks.append(_render_excel_rows(rows, flatten=False))
return "\n\n".join(blocks) or "_Keine Inhalte_"
blocks.append(_render_excel_worksheet_html(
sheet, workbook,
bounds=(min_col, min_row, max_col, min(max_row, rendered_max_row)),
))
if max_rows and sheet.max_row > max_rows:
blocks.append("<p><em>%s</em></p>" % escape(_("Preview limited to %(rows)s of %(total)s rows.") % {"rows": max_rows, "total": sheet.max_row}))
return "\n".join(blocks) or "<p><em>Keine Inhalte</em></p>"
def _pdf(content):
@@ -199,7 +412,7 @@ def _pdf(content):
text = (page.extract_text() or "").strip()
if text:
text = re.sub(r"[ \t]+\n", "\n", text)
pages.append(f"## Seite {number}\n\n{text}")
pages.append("## %s\n\n%s" % (_("Page %(number)s") % {"number": number}, text))
if not pages:
raise ImportFailure("Das PDF enthält keinen extrahierbaren Text. Für Scans ist OCR erforderlich.")
return ImportResult("\n\n".join(pages), ["PDF-Layout und Bilder können nicht vollständig übernommen werden."])
raise ImportFailure(_("The PDF contains no extractable text. Scanned documents require OCR."))
return ImportResult("\n\n".join(pages), [_("PDF layout and images cannot be imported completely.")])
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("netbox_documentation", "0004_excelimportpreview"),
("tenancy", "0001_squashed_0012"),
]
operations = [
migrations.AddField(
model_name="document",
name="tenant_group",
field=models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,
related_name="documentation_documents", to="tenancy.tenantgroup",
),
),
migrations.AddField(
model_name="document",
name="tenant",
field=models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,
related_name="documentation_documents", to="tenancy.tenant",
),
),
migrations.AddField(
model_name="documentcategory",
name="tenant_group",
field=models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,
related_name="documentation_categories", to="tenancy.tenantgroup",
),
),
migrations.AddField(
model_name="documentcategory",
name="tenant",
field=models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,
related_name="documentation_categories", to="tenancy.tenant",
),
),
]
@@ -0,0 +1,50 @@
# Generated by Django 6.1.1 on 2026-10-13 12:06
import taggit.managers
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('netbox_documentation', '0005_document_tenancy'),
]
operations = [
migrations.RemoveField(
model_name='document',
name='tags',
),
migrations.RemoveField(
model_name='documentassignment',
name='tags',
),
migrations.RemoveField(
model_name='documentattachment',
name='tags',
),
migrations.RemoveField(
model_name='documentcategory',
name='tags',
),
migrations.AddField(
model_name='document',
name='tags',
field=taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag'),
),
migrations.AddField(
model_name='documentassignment',
name='tags',
field=taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag'),
),
migrations.AddField(
model_name='documentattachment',
name='tags',
field=taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag'),
),
migrations.AddField(
model_name='documentcategory',
name='tags',
field=taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag'),
),
]
+63 -24
View File
@@ -3,25 +3,36 @@ from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from pathlib import Path
import uuid
from netbox.models import NetBoxModel
BODY_FORMAT_CHOICES = (("html", "Rich Text"), ("markdown", "Markdown"))
BODY_FORMAT_CHOICES = (("html", _("Rich text")), ("markdown", _("Markdown")))
class Document(NetBoxModel):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
body = models.TextField(blank=True, help_text="Markdown")
body_format = models.CharField(max_length=10, choices=BODY_FORMAT_CHOICES, default="html")
summary = models.CharField(max_length=500, blank=True)
is_published = models.BooleanField(default=True)
category = models.ForeignKey("DocumentCategory", on_delete=models.SET_NULL, null=True, blank=True, related_name="documents")
title = models.CharField(_("title"), max_length=200)
slug = models.SlugField(_("slug"), max_length=200, unique=True)
body = models.TextField(_("body"), blank=True, help_text=_("Markdown"))
body_format = models.CharField(_("body format"), max_length=10, choices=BODY_FORMAT_CHOICES, default="html")
summary = models.CharField(_("summary"), max_length=500, blank=True)
is_published = models.BooleanField(_("published"), default=True)
category = models.ForeignKey("DocumentCategory", on_delete=models.SET_NULL, null=True, blank=True, related_name="documents", verbose_name=_("folder"))
tenant_group = models.ForeignKey(
"tenancy.TenantGroup", on_delete=models.SET_NULL, null=True, blank=True,
related_name="documentation_documents", verbose_name=_("tenant group"),
)
tenant = models.ForeignKey(
"tenancy.Tenant", on_delete=models.SET_NULL, null=True, blank=True,
related_name="documentation_documents", verbose_name=_("tenant"),
)
class Meta:
ordering = ("title",)
verbose_name = _("document")
verbose_name_plural = _("documents")
permissions = (("import_document", "Can import office documents"),)
def __str__(self):
@@ -60,19 +71,31 @@ class Document(NetBoxModel):
"padding-left", "padding-right", "padding-top", "text-align", "text-decoration",
"text-indent", "vertical-align", "white-space", "width",
})
return bleach.clean(value, tags=tags, attributes=attributes, protocols=("http", "https", "mailto"), css_sanitizer=css)
from .highlighting import highlight_code_blocks
cleaned = bleach.clean(value, tags=tags, attributes=attributes, protocols=("http", "https", "mailto"), css_sanitizer=css)
return highlight_code_blocks(cleaned)
class DocumentCategory(NetBoxModel):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
description = models.CharField(max_length=500, blank=True)
name = models.CharField(_("name"), max_length=100)
slug = models.SlugField(_("slug"), max_length=100)
parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children", verbose_name=_("parent folder"))
description = models.CharField(_("description"), max_length=500, blank=True)
tenant_group = models.ForeignKey(
"tenancy.TenantGroup", on_delete=models.SET_NULL, null=True, blank=True,
related_name="documentation_categories", verbose_name=_("tenant group"),
)
tenant = models.ForeignKey(
"tenancy.Tenant", on_delete=models.SET_NULL, null=True, blank=True,
related_name="documentation_categories", verbose_name=_("tenant"),
)
class Meta:
ordering = ("name",)
constraints = [models.UniqueConstraint(fields=("parent", "slug"), name="%(app_label)s_%(class)s_unique_parent_slug")]
verbose_name_plural = "document categories"
verbose_name = _("folder")
verbose_name_plural = _("folders")
def __str__(self):
names = [self.name]
@@ -87,6 +110,18 @@ class DocumentCategory(NetBoxModel):
def get_absolute_url(self):
return reverse("plugins:netbox_documentation:documentcategory", args=[self.pk])
@property
def ancestors(self):
"""Ancestor folders from the root down to (excluding) this one, for breadcrumbs."""
result = []
parent = self.parent
seen = {self.pk}
while parent and parent.pk not in seen:
result.append(parent)
seen.add(parent.pk)
parent = parent.parent
return list(reversed(result))
def clean(self):
super().clean()
from django.core.exceptions import ValidationError
@@ -94,20 +129,22 @@ class DocumentCategory(NetBoxModel):
seen = {self.pk} if self.pk else set()
while parent:
if parent.pk in seen:
raise ValidationError({"parent": "Ein Ordner kann nicht sich selbst oder einem Unterordner untergeordnet werden."})
raise ValidationError({"parent": _("A folder cannot be placed inside itself or one of its subfolders.")})
seen.add(parent.pk)
parent = parent.parent
class DocumentAssignment(NetBoxModel):
document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name="assignments")
assigned_object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
assigned_object_id = models.PositiveBigIntegerField()
document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name="assignments", verbose_name=_("document"))
assigned_object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, verbose_name=_("object type"))
assigned_object_id = models.PositiveBigIntegerField(_("object ID"))
assigned_object = GenericForeignKey("assigned_object_type", "assigned_object_id")
note = models.CharField(max_length=200, blank=True)
note = models.CharField(_("note"), max_length=200, blank=True)
class Meta:
ordering = ("document", "assigned_object_type", "assigned_object_id")
verbose_name = _("document assignment")
verbose_name_plural = _("document assignments")
constraints = [models.UniqueConstraint(
fields=("document", "assigned_object_type", "assigned_object_id"),
name="%(app_label)s_%(class)s_unique_assignment",
@@ -127,14 +164,16 @@ def attachment_upload_path(instance, filename):
class DocumentAttachment(NetBoxModel):
document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name="attachments")
file = models.FileField(upload_to=attachment_upload_path)
original_name = models.CharField(max_length=255)
content_type = models.CharField(max_length=100, blank=True)
size = models.PositiveBigIntegerField(default=0)
document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name="attachments", verbose_name=_("document"))
file = models.FileField(_("file"), upload_to=attachment_upload_path)
original_name = models.CharField(_("original name"), max_length=255)
content_type = models.CharField(_("content type"), max_length=100, blank=True)
size = models.PositiveBigIntegerField(_("size"), default=0)
class Meta:
ordering = ("original_name",)
verbose_name = _("attachment")
verbose_name_plural = _("attachments")
def __str__(self):
return self.original_name
+11 -10
View File
@@ -1,20 +1,21 @@
from django.utils.translation import gettext_lazy as _
from netbox.plugins import PluginMenu, PluginMenuButton, PluginMenuItem
from netbox.choices import ButtonColorChoices
menu = PluginMenu(
label="Dokumentation",
groups=(("Wiki", (
PluginMenuItem(link="plugins:netbox_documentation:document_list", link_text="Dokumentationen", buttons=(
PluginMenuButton(link="plugins:netbox_documentation:document_add", title="Neu", icon_class="mdi mdi-plus-thick", color=ButtonColorChoices.GREEN),
PluginMenuButton(link="plugins:netbox_documentation:document_import", title="Import", icon_class="mdi mdi-file-import", color=ButtonColorChoices.BLUE),
label=_("Documentation"),
groups=((_("Wiki"), (
PluginMenuItem(link="plugins:netbox_documentation:document_tree", link_text=_("Documents"), buttons=(
PluginMenuButton(link="plugins:netbox_documentation:document_add", title=_("New"), icon_class="mdi mdi-plus-thick", color=ButtonColorChoices.GREEN),
PluginMenuButton(link="plugins:netbox_documentation:document_import", title=_("Import"), icon_class="mdi mdi-file-import", color=ButtonColorChoices.BLUE),
)),
PluginMenuItem(link="plugins:netbox_documentation:documentassignment_list", link_text="Zuordnungen", buttons=(
PluginMenuButton(link="plugins:netbox_documentation:documentassignment_add", title="Zuordnen", icon_class="mdi mdi-link-plus", color=ButtonColorChoices.GREEN),
PluginMenuItem(link="plugins:netbox_documentation:documentassignment_list", link_text=_("Assignments"), buttons=(
PluginMenuButton(link="plugins:netbox_documentation:documentassignment_add", title=_("Assign"), icon_class="mdi mdi-link-plus", color=ButtonColorChoices.GREEN),
)),
PluginMenuItem(link="plugins:netbox_documentation:documentcategory_list", link_text="Ordner & Kategorien", buttons=(
PluginMenuButton(link="plugins:netbox_documentation:documentcategory_add", title="Ordner erstellen", icon_class="mdi mdi-folder-plus", color=ButtonColorChoices.GREEN),
PluginMenuItem(link="plugins:netbox_documentation:documentcategory_tree", link_text=_("Folders & categories"), buttons=(
PluginMenuButton(link="plugins:netbox_documentation:documentcategory_add", title=_("Create folder"), icon_class="mdi mdi-folder-plus", color=ButtonColorChoices.GREEN),
)),
PluginMenuItem(link="plugins:netbox_documentation:document_archive", link_text="ZIP Export & Import"),
PluginMenuItem(link="plugins:netbox_documentation:document_archive", link_text=_("ZIP export & import")),
)),),
icon_class="mdi mdi-book-open-page-variant",
)
+7 -6
View File
@@ -1,31 +1,32 @@
import django_tables2 as tables
from django.utils.translation import gettext_lazy as _
from netbox.tables import NetBoxTable, columns
from .models import Document, DocumentAssignment, DocumentCategory
class DocumentTable(NetBoxTable):
title = tables.Column(linkify=True)
assignments = tables.Column(accessor="assignments.count", verbose_name="Zuordnungen", orderable=False)
assignments = tables.Column(accessor="assignments.count", verbose_name=_("Assignments"), orderable=False)
actions = columns.ActionsColumn(actions=("edit", "delete"))
class Meta(NetBoxTable.Meta):
model = Document
fields = ("pk", "title", "category", "summary", "is_published", "assignments", "last_updated", "actions")
fields = ("pk", "title", "category", "tenant_group", "tenant", "summary", "is_published", "assignments", "last_updated", "actions")
class DocumentCategoryTable(NetBoxTable):
name = tables.Column(linkify=True, verbose_name="Ordner")
document_count = tables.Column(accessor="documents.count", verbose_name="Dokumente", orderable=False)
name = tables.Column(linkify=True, verbose_name=_("Folder"))
document_count = tables.Column(accessor="documents.count", verbose_name=_("Documents"), orderable=False)
actions = columns.ActionsColumn(actions=("edit", "delete"))
class Meta(NetBoxTable.Meta):
model = DocumentCategory
fields = ("pk", "name", "parent", "description", "document_count", "actions")
fields = ("pk", "name", "parent", "tenant_group", "tenant", "description", "document_count", "actions")
class AssignmentTable(NetBoxTable):
document = tables.Column(linkify=True)
assigned_object = tables.Column(linkify=True, verbose_name="NetBox-Objekt")
assigned_object = tables.Column(linkify=True, verbose_name=_("NetBox object"))
actions = columns.ActionsColumn(actions=("edit", "delete"))
class Meta(NetBoxTable.Meta):
@@ -1,4 +1,5 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% load helpers %}
{% block head %}
{{ block.super }}
@@ -40,6 +41,52 @@
.documentation-content .doc-cell-blue { background: #dbeafe !important; color: #212529; }
.documentation-content .doc-cell-middle { vertical-align: middle !important; }
.documentation-content p { max-width: 90rem; }
.documentation-content .doc-code-block { position: relative; margin: 0 0 1rem; }
.documentation-content pre {
margin: 0;
padding: .85rem 4.5rem .85rem 1rem;
background: #1e1e1e !important;
color: #e9ecef !important;
border-radius: 6px;
font-family: Consolas, 'Courier New', monospace;
font-size: 10pt;
line-height: 1.5;
white-space: pre-wrap;
overflow-x: auto;
}
.documentation-content pre * { background: transparent !important; font-family: inherit !important; }
.documentation-content pre ::selection,
.documentation-content pre::selection { background: #4c8bf5 !important; color: #fff !important; }
.documentation-content .doc-code-copy {
position: absolute; top: .4rem; right: .4rem;
padding: .15rem .5rem; font-size: .75rem;
color: #e9ecef; background: rgba(255,255,255,.1);
border: 1px solid rgba(255,255,255,.25); border-radius: 4px;
}
.documentation-content .doc-code-copy:hover { background: rgba(255,255,255,.2); }
.documentation-content .doc-code-lang {
position: absolute; top: .55rem; right: 6.2rem;
font-size: .7rem; color: #9da5b4; text-transform: uppercase; letter-spacing: .03em;
pointer-events: none; user-select: none;
}
.documentation-content pre.doc-hl[data-lang] { padding-right: 11rem; }
/* Syntax highlighting (Pygments token classes) - VS Code "Dark+" colours */
.documentation-content pre.doc-hl { color: #d4d4d4 !important; }
.doc-hl .k, .doc-hl .kc, .doc-hl .kd, .doc-hl .kr, .doc-hl .kp, .doc-hl .ow, .doc-hl .nt, .doc-hl .bp { color: #569cd6; }
.doc-hl .kn, .doc-hl .cp, .doc-hl .cpf { color: #c586c0; }
.doc-hl .kt, .doc-hl .nc, .doc-hl .nn, .doc-hl .ne { color: #4ec9b0; }
.doc-hl .nf, .doc-hl .fm, .doc-hl .nb, .doc-hl .nd { color: #dcdcaa; }
.doc-hl .n, .doc-hl .nv, .doc-hl .vi, .doc-hl .vg, .doc-hl .vc, .doc-hl .na, .doc-hl .py, .doc-hl .nl { color: #9cdcfe; }
.doc-hl .s, .doc-hl .s1, .doc-hl .s2, .doc-hl .sa, .doc-hl .sb, .doc-hl .sc, .doc-hl .sd, .doc-hl .sh,
.doc-hl .si, .doc-hl .sx, .doc-hl .sr, .doc-hl .ss, .doc-hl .dl { color: #ce9178; }
.doc-hl .se { color: #d7ba7d; }
.doc-hl .m, .doc-hl .mi, .doc-hl .mf, .doc-hl .mh, .doc-hl .mo, .doc-hl .mb, .doc-hl .il { color: #b5cea8; }
.doc-hl .c, .doc-hl .c1, .doc-hl .cm, .doc-hl .ch, .doc-hl .cs, .doc-hl .sd { color: #6a9955; }
.doc-hl .o, .doc-hl .p { color: #d4d4d4; }
.doc-hl .gh, .doc-hl .gu { color: #569cd6; font-weight: bold; }
.doc-hl .gi { color: #b5cea8; }
.doc-hl .gd { color: #ce9178; }
.doc-hl .err { color: #f44747; }
.documentation-content table { cursor: zoom-in; }
#documentation-viewer.documentation-page-focus {
position: fixed;
@@ -63,26 +110,30 @@
{% endblock head %}
{% block extra_controls %}
<button type="button" id="documentation-fullscreen" class="btn btn-outline-secondary">
<i class="mdi mdi-arrow-expand-all"></i> Großansicht
<i class="mdi mdi-arrow-expand-all"></i> {% trans "Focus view" %}
</button>
<a href="{% url 'plugins:netbox_documentation:document_print' pk=object.pk %}" target="_blank" class="btn btn-outline-secondary">
<i class="mdi mdi-printer"></i> Drucken / PDF
<i class="mdi mdi-printer"></i> {% trans "Print / PDF" %}
</a>
{% endblock extra_controls %}
{% block content %}
<div class="row">
<div class="col col-md-9" id="documentation-viewer">
<h1 class="fullscreen-document-title">{{ object.title }}</h1>
<button type="button" class="btn btn-secondary fullscreen-exit" id="documentation-fullscreen-exit"><i class="mdi mdi-arrow-collapse-all"></i> Großansicht beenden</button>
<button type="button" class="btn btn-secondary fullscreen-exit" id="documentation-fullscreen-exit"><i class="mdi mdi-arrow-collapse-all"></i> {% trans "Exit focus view" %}</button>
{% if object.summary %}<p class="lead">{{ object.summary }}</p>{% endif %}
<div class="card"><div class="card-body rendered-markdown documentation-content">{{ object.rendered_body|safe }}</div></div>
</div>
<div class="col col-md-3">
{% if object.category %}<div class="card mb-3"><h5 class="card-header">Ordner</h5><a class="list-group-item list-group-item-action" href="{{ object.category.get_absolute_url }}"><i class="mdi mdi-folder"></i> {{ object.category }}</a></div>{% endif %}
<div class="card"><h5 class="card-header">Zuordnungen</h5><div class="list-group list-group-flush">
{% for assignment in object.assignments.all %}<a class="list-group-item" href="{{ assignment.assigned_object.get_absolute_url }}">{{ assignment.assigned_object_type }}: {{ assignment.assigned_object }}</a>{% empty %}<div class="list-group-item text-muted">Noch nicht zugeordnet</div>{% endfor %}
{% if object.tenant_group or object.tenant %}<div class="card mb-3"><h5 class="card-header">{% trans "Tenancy" %}</h5><div class="list-group list-group-flush">
{% if object.tenant_group %}<a class="list-group-item list-group-item-action" href="{{ object.tenant_group.get_absolute_url }}"><i class="mdi mdi-account-group"></i> {{ object.tenant_group }}</a>{% endif %}
{% if object.tenant %}<a class="list-group-item list-group-item-action" href="{{ object.tenant.get_absolute_url }}"><i class="mdi mdi-domain"></i> {{ object.tenant }}</a>{% endif %}
</div></div>{% endif %}
{% if object.category %}<div class="card mb-3"><h5 class="card-header">{% trans "Folder" %}</h5><a class="list-group-item list-group-item-action" href="{{ object.category.get_absolute_url }}"><i class="mdi mdi-folder"></i> {{ object.category }}</a></div>{% endif %}
<div class="card"><h5 class="card-header">{% trans "Assignments" %}</h5><div class="list-group list-group-flush">
{% for assignment in object.assignments.all %}<a class="list-group-item" href="{{ assignment.assigned_object.get_absolute_url }}">{{ assignment.assigned_object_type }}: {{ assignment.assigned_object }}</a>{% empty %}<div class="list-group-item text-muted">{% trans "Not assigned yet" %}</div>{% endfor %}
</div></div>
{% if object.attachments.all %}<div class="card mt-3"><h5 class="card-header">Originaldateien</h5><div class="list-group list-group-flush">
{% if object.attachments.all %}<div class="card mt-3"><h5 class="card-header">{% trans "Original files" %}</h5><div class="list-group list-group-flush">
{% for attachment in object.attachments.all %}<a class="list-group-item" href="{{ attachment.file.url }}">{{ attachment.original_name }}</a>{% endfor %}
</div></div>{% endif %}
</div>
@@ -109,13 +160,48 @@
openButton.addEventListener('click', openViewer);
closeButton.addEventListener('click', closeViewer);
viewer.querySelectorAll('.documentation-content table').forEach(table => {
table.title = 'Tabelle in Großansicht öffnen';
table.title = '{{ _("Open table in focus view")|escapejs }}';
table.addEventListener('click', event => {
if (viewer.classList.contains('documentation-page-focus')) return;
if (event.target.closest('a, button, input, select, textarea')) return;
openViewer();
});
});
viewer.querySelectorAll('.documentation-content pre').forEach(pre => {
const wrapper = document.createElement('div');
wrapper.className = 'doc-code-block';
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
const copyButton = document.createElement('button');
copyButton.type = 'button';
copyButton.className = 'doc-code-copy';
copyButton.innerHTML = '<i class="mdi mdi-content-copy"></i> {{ _("Copy")|escapejs }}';
copyButton.addEventListener('click', async () => {
const text = pre.innerText.trimEnd();
try {
await navigator.clipboard.writeText(text);
} catch (error) {
// Fallback for plain-HTTP deployments without Clipboard API.
const area = document.createElement('textarea');
area.value = text;
area.style.position = 'fixed';
area.style.opacity = '0';
document.body.appendChild(area);
area.select();
document.execCommand('copy');
area.remove();
}
copyButton.innerHTML = '<i class="mdi mdi-check"></i> {{ _("Copied")|escapejs }}';
setTimeout(() => { copyButton.innerHTML = '<i class="mdi mdi-content-copy"></i> {{ _("Copy")|escapejs }}'; }, 1500);
});
wrapper.appendChild(copyButton);
if (pre.dataset.lang) {
const label = document.createElement('span');
label.className = 'doc-code-lang';
label.textContent = pre.dataset.lang;
wrapper.appendChild(label);
}
});
document.addEventListener('keydown', event => {
if (event.key === 'Escape' && viewer.classList.contains('documentation-page-focus')) closeViewer();
});
@@ -1,34 +1,35 @@
{% extends 'base/layout.html' %}
{% load i18n %}
{% load form_helpers %}
{% block title %}Dokumentationsarchiv{% endblock %}
{% block title %}{% trans "Documentation archive" %}{% endblock %}
{% block content %}
<div class="row g-4">
<div class="col-12 col-xl-6">
<div class="card h-100">
<h5 class="card-header"><i class="mdi mdi-folder-zip"></i> Dokumentationen exportieren</h5>
<h5 class="card-header"><i class="mdi mdi-folder-zip"></i> {% trans "Export documents" %}</h5>
<div class="card-body">
<p>Mehrere Ordner suchen und hinzufügen. Alle enthaltenen Dokumentationen werden gemeinsam mit Objektzuordnungen und Anhängen heruntergeladen.</p>
<p>{% trans "Search for and add several folders. All contained documents are downloaded together with their object assignments and attachments." %}</p>
<form method="post">
{% csrf_token %}
<input type="hidden" name="action" value="export">
{% render_form export_form %}
<button type="submit" class="btn btn-primary"><i class="mdi mdi-download"></i> ZIP herunterladen</button>
<button type="submit" class="btn btn-primary"><i class="mdi mdi-download"></i> {% trans "Download ZIP" %}</button>
</form>
</div>
</div>
</div>
<div class="col-12 col-xl-6">
<div class="card h-100">
<h5 class="card-header"><i class="mdi mdi-folder-upload"></i> Dokumentationen importieren</h5>
<h5 class="card-header"><i class="mdi mdi-folder-upload"></i> {% trans "Import documents" %}</h5>
<div class="card-body">
<p>Ein zuvor mit diesem Plugin erzeugtes ZIP-Archiv hochladen. Nicht vorhandene NetBox-Zielobjekte werden sicher übersprungen.</p>
<p>{% trans "Upload a ZIP archive previously created with this plugin. Missing NetBox target objects are skipped safely." %}</p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="action" value="import">
{% render_form import_form %}
<button type="submit" class="btn btn-primary"><i class="mdi mdi-upload"></i> ZIP importieren</button>
<button type="submit" class="btn btn-primary"><i class="mdi mdi-upload"></i> {% trans "Import ZIP" %}</button>
</form>
</div>
</div>
@@ -1,4 +1,5 @@
{% extends 'generic/object_edit.html' %}
{% load i18n %}
{% block javascript %}
{{ block.super }}
<style>
@@ -19,7 +20,7 @@
if (editor) {
const warning = document.createElement('div');
warning.className = 'alert alert-warning';
warning.textContent = 'Der Rich-Text-Editor konnte nicht vom lokalen Plugin-Endpunkt geladen werden. Bitte Browser-Konsole und Netzwerkprotokoll prüfen.';
warning.textContent = '{{ _("The rich text editor could not be loaded from the local plugin endpoint. Please check the browser console and network log.")|escapejs }}';
editor.parentNode.insertBefore(warning, editor);
}
return;
@@ -29,12 +30,15 @@
base_url: editorAssetBase.replace(/\/$/, ''),
suffix: '.min',
license_key: 'gpl',
{% get_current_language as LANGUAGE_CODE %}{% if LANGUAGE_CODE|slice:":2" == 'de' %}language: 'de',
language_url: editorAssetBase.replace(/\/$/, '') + '/langs/de.js',
{% endif %}
height: 650,
menubar: 'file edit view insert format tools table help',
plugins: 'advlist anchor autolink charmap code fullscreen image link lists media preview searchreplace table visualblocks wordcount',
plugins: 'advlist anchor autolink charmap code codesample fullscreen image link lists media preview searchreplace table visualblocks wordcount',
toolbar: [
'undo redo | blocks styles fontfamily fontsize | bold italic underline strikethrough | forecolor backcolor',
'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table tablecellcolor link image media | removeformat code fullscreen'
'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table tablecellcolor link image media codesample | removeformat code fullscreen'
],
toolbar_mode: 'sliding',
table_toolbar: 'tableprops tablecellprops tablecellcolor | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells | tabledelete',
@@ -46,29 +50,29 @@
table_default_attributes: {border: '1'},
table_default_styles: {'border-collapse': 'collapse'},
table_class_list: [
{title: 'Standard mit Rahmen', value: 'doc-table-bordered'},
{title: 'Kompakt', value: 'doc-table-compact'},
{title: 'Gestreifte Zeilen', value: 'doc-table-striped'},
{title: 'Blaue Kopfzeile', value: 'doc-table-header-blue'},
{title: 'Grüne Kopfzeile', value: 'doc-table-header-green'},
{title: 'Dunkle Kopfzeile', value: 'doc-table-header-dark'},
{title: 'Ohne Rahmen', value: 'doc-table-borderless'},
{title: 'Volle Breite', value: 'doc-table-full-width'}
{title: '{{ _("Standard with borders")|escapejs }}', value: 'doc-table-bordered'},
{title: '{{ _("Compact")|escapejs }}', value: 'doc-table-compact'},
{title: '{{ _("Striped rows")|escapejs }}', value: 'doc-table-striped'},
{title: '{{ _("Blue header")|escapejs }}', value: 'doc-table-header-blue'},
{title: '{{ _("Green header")|escapejs }}', value: 'doc-table-header-green'},
{title: '{{ _("Dark header")|escapejs }}', value: 'doc-table-header-dark'},
{title: '{{ _("No borders")|escapejs }}', value: 'doc-table-borderless'},
{title: '{{ _("Full width")|escapejs }}', value: 'doc-table-full-width'}
],
table_cell_class_list: [
{title: 'Normal', value: ''},
{title: 'Gelb hervorheben', value: 'doc-cell-yellow'},
{title: 'Grün hervorheben', value: 'doc-cell-green'},
{title: 'Rot hervorheben', value: 'doc-cell-red'},
{title: 'Blau hervorheben', value: 'doc-cell-blue'},
{title: 'Vertikal mittig', value: 'doc-cell-middle'}
{title: '{{ _("Normal")|escapejs }}', value: ''},
{title: '{{ _("Highlight yellow")|escapejs }}', value: 'doc-cell-yellow'},
{title: '{{ _("Highlight green")|escapejs }}', value: 'doc-cell-green'},
{title: '{{ _("Highlight red")|escapejs }}', value: 'doc-cell-red'},
{title: '{{ _("Highlight blue")|escapejs }}', value: 'doc-cell-blue'},
{title: '{{ _("Vertically centred")|escapejs }}', value: 'doc-cell-middle'}
],
style_formats_merge: true,
style_formats: [
{title: 'Tabellenzelle: Gelb', selector: 'td,th', classes: 'doc-cell-yellow'},
{title: 'Tabellenzelle: Grün', selector: 'td,th', classes: 'doc-cell-green'},
{title: 'Tabellenzelle: Rot', selector: 'td,th', classes: 'doc-cell-red'},
{title: 'Tabellenzelle: Blau', selector: 'td,th', classes: 'doc-cell-blue'}
{title: '{{ _("Table cell: yellow")|escapejs }}', selector: 'td,th', classes: 'doc-cell-yellow'},
{title: '{{ _("Table cell: green")|escapejs }}', selector: 'td,th', classes: 'doc-cell-green'},
{title: '{{ _("Table cell: red")|escapejs }}', selector: 'td,th', classes: 'doc-cell-red'},
{title: '{{ _("Table cell: blue")|escapejs }}', selector: 'td,th', classes: 'doc-cell-blue'}
],
font_family_formats: 'Arial=arial,helvetica,sans-serif; Calibri=calibri,arial,sans-serif; Courier New=courier new,courier,monospace; Georgia=georgia,palatino,serif; Times New Roman=times new roman,times,serif; Verdana=verdana,geneva,sans-serif',
font_size_formats: '8pt 9pt 10pt 11pt 12pt 14pt 16pt 18pt 20pt 24pt 28pt 32pt 36pt 48pt',
@@ -88,9 +92,24 @@
.doc-cell-red { background: #ffe3e3 !important; }
.doc-cell-blue { background: #dbeafe !important; }
.doc-cell-middle { vertical-align: middle !important; }
pre { background: #1e1e1e; color: #e9ecef; padding: .75rem 1rem; border-radius: 6px; font-family: Consolas, 'Courier New', monospace; font-size: 10pt; white-space: pre-wrap; }
pre ::selection, pre::selection { background: #4c8bf5; color: #fff; }
`,
codesample_global_prismjs: false,
codesample_languages: [
{text: 'Bash / Shell', value: 'bash'},
{text: 'PowerShell', value: 'powershell'},
{text: '{{ _("Cisco / network configuration")|escapejs }}', value: 'none'},
{text: 'Python', value: 'python'},
{text: 'JSON', value: 'json'},
{text: 'YAML', value: 'yaml'},
{text: 'SQL', value: 'sql'},
{text: 'HTML/XML', value: 'markup'},
{text: 'JavaScript', value: 'javascript'},
{text: '{{ _("Plain text")|escapejs }}', value: 'plaintext'}
],
browser_spellcheck: true,
contextmenu: 'link image table',
contextmenu: 'link image table codesample',
promotion: false,
branding: false,
convert_unsafe_embeds: true,
@@ -101,6 +120,30 @@
paste_convert_word_fake_lists: true,
smart_paste: true,
images_reuse_filename: true,
file_picker_types: 'image',
file_picker_callback: (callback, value, meta) => {
if (meta.filetype !== 'image') return;
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/png,image/jpeg,image/gif,image/webp';
picker.addEventListener('change', () => {
const file = picker.files && picker.files[0];
if (!file) return;
const allowedTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
if (!allowedTypes.includes(file.type)) {
window.alert('{{ _("Supported formats are PNG, JPEG, GIF and WebP.")|escapejs }}');
return;
}
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result, {
alt: file.name,
title: file.name
}));
reader.addEventListener('error', () => window.alert('{{ _("The image could not be read.")|escapejs }}'));
reader.readAsDataURL(file);
}, {once: true});
picker.click();
},
relative_urls: false,
setup: editor => {
const selectedTableCells = () => {
@@ -131,13 +174,13 @@
picker.click();
};
const palette = [
['Gelb', '#fff3bf'], ['Grün', '#d3f9d8'], ['Blau', '#dbeafe'],
['Rot', '#ffe3e3'], ['Orange', '#ffe8cc'], ['Grau', '#e9ecef'],
['Dunkelgrün', '#a5bf60'], ['Dunkelblau', '#206bc4'], ['Dunkelgrau', '#343a40']
['{{ _("Yellow")|escapejs }}', '#fff3bf'], ['{{ _("Green")|escapejs }}', '#d3f9d8'], ['{{ _("Blue")|escapejs }}', '#dbeafe'],
['{{ _("Red")|escapejs }}', '#ffe3e3'], ['{{ _("Orange")|escapejs }}', '#ffe8cc'], ['{{ _("Grey")|escapejs }}', '#e9ecef'],
['{{ _("Dark green")|escapejs }}', '#a5bf60'], ['{{ _("Dark blue")|escapejs }}', '#206bc4'], ['{{ _("Dark grey")|escapejs }}', '#343a40']
];
editor.ui.registry.addMenuButton('tablecellcolor', {
icon: 'highlight-bg-color',
tooltip: 'Farbeimer für Tabellenzellen',
tooltip: '{{ _("Table cell colour")|escapejs }}',
fetch: callback => callback([
...palette.map(([name, color]) => ({
type: 'menuitem',
@@ -145,8 +188,8 @@
onAction: () => applyCellColor(color)
})),
{type: 'separator'},
{type: 'menuitem', text: 'Eigene Farbe …', onAction: chooseCellColor},
{type: 'menuitem', text: 'Zellfarbe entfernen', onAction: () => applyCellColor('')}
{type: 'menuitem', text: '{{ _("Custom colour …")|escapejs }}', onAction: chooseCellColor},
{type: 'menuitem', text: '{{ _("Remove cell colour")|escapejs }}', onAction: () => applyCellColor('')}
])
});
}
@@ -163,7 +206,7 @@
credentials: 'same-origin'
}).then(async response => {
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || 'Upload fehlgeschlagen');
if (!response.ok) throw new Error(payload.error || '{{ _("Upload failed")|escapejs }}');
resolve(payload.location);
}).catch(error => reject(error.message));
})
@@ -175,6 +218,6 @@
{% block pre_form_fields %}
{% if not object.pk %}
<div class="alert alert-info">Speichere die neue Dokumentation einmal. Danach können Bilder direkt über die Editor-Werkzeugleiste hochgeladen werden.</div>
<div class="alert alert-info">{% trans "Pasted images are stored automatically as media of the new document when it is first saved. After the first save, direct image upload is also available." %}</div>
{% endif %}
{% endblock pre_form_fields %}
@@ -1,15 +1,16 @@
{% extends 'base/layout.html' %}
{% load i18n %}
{% load form_helpers %}
{% block title %}Dokument importieren{% endblock %}
{% block title %}{% trans "Import document" %}{% endblock %}
{% block content %}
<div class="row justify-content-center"><div class="col col-md-8"><div class="card">
<h5 class="card-header">Word, Excel oder PDF importieren</h5>
<h5 class="card-header">{% trans "Import Word, Excel or PDF" %}</h5>
<div class="card-body"><form method="post" enctype="multipart/form-data">{% csrf_token %}{% render_form form %}
<div class="text-muted mb-3">
Importhinweise
<span class="mdi mdi-help-circle-outline" data-bs-toggle="tooltip" title="DOCX übernimmt Überschriften, Listen und Tabellen. Beim normalen XLSX-Import werden alle Blätter zusammengeführt. Der Mehrblattimport erzeugt je Blatt eine Dokumentation im Zielordner. PDF benötigt eine echte Textebene; Scan-OCR ist nicht enthalten." aria-label="Importhinweise"></span>
{% trans "Import notes" %}
<span class="mdi mdi-help-circle-outline" data-bs-toggle="tooltip" title="{% trans "DOCX keeps headings, lists and tables. A regular XLSX import merges all sheets. The multi-sheet import creates one document per sheet in the target folder. PDF requires a real text layer; OCR for scans is not included." %}" aria-label="{% trans "Import notes" %}"></span>
</div>
<button type="submit" class="btn btn-primary">Importieren</button>
<button type="submit" class="btn btn-primary">{% trans "Import" %}</button>
</form></div>
</div></div></div>
{% endblock %}
@@ -1,9 +1,10 @@
{% load i18n %}
<!doctype html>
<html lang="de">
{% get_current_language as LANGUAGE_CODE %}<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ object.title }} – Druckansicht</title>
<title>{{ object.title }} – {% trans "Print view" %}</title>
<style>
:root { color-scheme: light; }
* { box-sizing: border-box; }
@@ -11,7 +12,9 @@
.toolbar { position: sticky; top: 0; z-index: 2; display: flex; justify-content: center; gap: .75rem; padding: .8rem; background: #fff; border-bottom: 1px solid #ccd2d8; }
.toolbar button, .toolbar a { border: 1px solid #6c757d; border-radius: .3rem; padding: .55rem .9rem; background: #fff; color: #212529; text-decoration: none; cursor: pointer; font: inherit; }
.toolbar button { color: #fff; background: #4263eb; border-color: #4263eb; }
.toolbar a.active { color: #fff; background: #495057; border-color: #495057; }
article { width: min(210mm, calc(100% - 2rem)); min-height: 297mm; margin: 1.5rem auto; padding: 18mm 17mm; background: #fff; box-shadow: 0 .2rem 1rem rgba(0,0,0,.12); }
article.landscape { width: min(297mm, calc(100% - 2rem)); min-height: 210mm; }
h1 { margin: 0 0 .25rem; font-size: 24pt; line-height: 1.2; }
.summary { color: #4b5563; font-size: 13pt; margin: 0 0 1rem; }
.meta { display: flex; flex-wrap: wrap; gap: .4rem 1.25rem; padding: .65rem 0; margin-bottom: 1.4rem; color: #6b7280; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; font-size: 9pt; }
@@ -32,7 +35,7 @@
.content .doc-cell-middle { vertical-align: middle; }
.content pre, .content code { white-space: pre-wrap; overflow-wrap: anywhere; font-family: Consolas, monospace; }
.content a { color: #174ea6; overflow-wrap: anywhere; }
@page { size: A4; margin: 15mm; }
@page { size: A4 {% if request.GET.orientation == 'landscape' %}landscape{% else %}portrait{% endif %}; margin: 15mm; }
@media print {
body { background: #fff; }
.toolbar { display: none !important; }
@@ -41,21 +44,32 @@
table, figure, img, pre, blockquote { break-inside: avoid; }
h1, h2, h3, h4 { break-after: avoid; }
}
.doc-hl .k, .doc-hl .kc, .doc-hl .kd, .doc-hl .kr, .doc-hl .kp, .doc-hl .ow, .doc-hl .nt, .doc-hl .bp { color: #0000ff; }
.doc-hl .kn, .doc-hl .cp, .doc-hl .cpf { color: #af00db; }
.doc-hl .kt, .doc-hl .nc, .doc-hl .nn, .doc-hl .ne { color: #267f99; }
.doc-hl .nf, .doc-hl .fm, .doc-hl .nb, .doc-hl .nd { color: #795e26; }
.doc-hl .n, .doc-hl .nv, .doc-hl .vi, .doc-hl .vg, .doc-hl .vc, .doc-hl .na, .doc-hl .py, .doc-hl .nl { color: #001080; }
.doc-hl .s, .doc-hl .s1, .doc-hl .s2, .doc-hl .sa, .doc-hl .sb, .doc-hl .sc, .doc-hl .sh,
.doc-hl .si, .doc-hl .sx, .doc-hl .sr, .doc-hl .ss, .doc-hl .dl, .doc-hl .se { color: #a31515; }
.doc-hl .m, .doc-hl .mi, .doc-hl .mf, .doc-hl .mh, .doc-hl .mo, .doc-hl .mb, .doc-hl .il { color: #098658; }
.doc-hl .c, .doc-hl .c1, .doc-hl .cm, .doc-hl .ch, .doc-hl .cs, .doc-hl .sd { color: #008000; }
</style>
</head>
<body>
<div class="toolbar">
<button type="button" onclick="window.print()">Drucken / Als PDF speichern</button>
<a href="{{ object.get_absolute_url }}">Zurück zur Dokumentation</a>
<button type="button" onclick="window.print()">{% trans "Print / save as PDF" %}</button>
<a href="?orientation=portrait"{% if request.GET.orientation != 'landscape' %} class="active"{% endif %}>{% trans "Portrait" %}</a>
<a href="?orientation=landscape"{% if request.GET.orientation == 'landscape' %} class="active"{% endif %}>{% trans "Landscape" %}</a>
<a href="{{ object.get_absolute_url }}">{% trans "Back to document" %}</a>
</div>
<article>
<article{% if request.GET.orientation == 'landscape' %} class="landscape"{% endif %}>
<header>
<h1>{{ object.title }}</h1>
{% if object.summary %}<p class="summary">{{ object.summary }}</p>{% endif %}
<div class="meta">
{% if object.category %}<span>Ordner: {{ object.category }}</span>{% endif %}
<span>Stand: {{ object.last_updated|date:"d.m.Y H:i" }}</span>
{% if object.assignments.all %}<span>Zugeordnet: {% for assignment in object.assignments.all %}{{ assignment.assigned_object }}{% if not forloop.last %}, {% endif %}{% endfor %}</span>{% endif %}
{% if object.category %}<span>{% trans "Folder" %}: {{ object.category }}</span>{% endif %}
<span>{% trans "Last updated" %}: {{ object.last_updated|date:"SHORT_DATETIME_FORMAT" }}</span>
{% if object.assignments.all %}<span>{% trans "Assigned to" %}: {% for assignment in object.assignments.all %}{{ assignment.assigned_object }}{% if not forloop.last %}, {% endif %}{% endfor %}</span>{% endif %}
</div>
</header>
<main class="content">{{ object.rendered_body|safe }}</main>
@@ -0,0 +1,586 @@
{% extends 'base/layout.html' %}
{% load i18n %}
{% block title %}{% trans "Documents" %}{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col d-flex justify-content-between align-items-center flex-wrap gap-2">
<input type="search" id="doc-tree-search" class="form-control" style="max-width: 20rem;" placeholder="{% trans "Search documents & folders…" %}">
<div class="d-flex gap-2">
{% if perms.netbox_documentation.add_document %}
<a href="{% url 'plugins:netbox_documentation:document_add' %}" class="btn btn-success" id="doc-add-document" data-base="{% url 'plugins:netbox_documentation:document_add' %}"><i class="mdi mdi-plus-thick"></i> {% trans "Add" %}</a>
{% endif %}
{% if perms.netbox_documentation.add_documentcategory %}
<a href="{% url 'plugins:netbox_documentation:documentcategory_add' %}" class="btn btn-outline-success" id="doc-add-folder" data-base="{% url 'plugins:netbox_documentation:documentcategory_add' %}"><i class="mdi mdi-folder-plus-outline"></i> {% trans "New folder" %}</a>
{% endif %}
<div class="btn-group" role="group" aria-label="{% trans "View" %}">
<button type="button" class="btn btn-outline-secondary" data-view="explorer" title="{% trans "Explorer view" %}"><i class="mdi mdi-view-grid-outline"></i> {% trans "Explorer" %}</button>
<button type="button" class="btn btn-outline-secondary" data-view="tree" title="{% trans "Tree view" %}"><i class="mdi mdi-file-tree"></i> {% trans "Tree" %}</button>
<a href="{% url 'plugins:netbox_documentation:document_list' %}" class="btn btn-outline-secondary" title="{% trans "List view" %}"><i class="mdi mdi-format-list-bulleted"></i> {% trans "List" %}</a>
</div>
</div>
</div>
</div>
{% if tree or uncategorized %}
<div class="card netbox-explorer" id="doc-explorer" hidden>
<div class="card-header d-flex align-items-center gap-2 py-2">
<button type="button" class="btn btn-sm btn-ghost-secondary" id="doc-explorer-back" title="{% trans "Back" %}"><i class="mdi mdi-arrow-left"></i></button>
<button type="button" class="btn btn-sm btn-ghost-secondary" id="doc-explorer-up" title="{% trans "Parent folder (Backspace)" %}"><i class="mdi mdi-arrow-up"></i></button>
<nav class="netbox-explorer-address flex-grow-1" id="doc-explorer-address"></nav>
<a href="#" class="btn btn-sm btn-ghost-secondary d-none" id="doc-explorer-props" title="{% trans "Folder details" %}"><i class="mdi mdi-information-outline"></i></a>
</div>
<div class="netbox-explorer-body">
<aside class="netbox-explorer-nav">
<div class="netbox-explorer-nav-row" data-folder="root"><span class="netbox-explorer-twisty"></span><i class="mdi mdi-folder-home text-warning"></i><span>{% trans "Documents" %}</span></div>
<ul class="list-unstyled mb-0">
{% for node in tree %}
{% include 'netbox_documentation/inc/explorer_nav_node.html' with node=node %}
{% endfor %}
</ul>
</aside>
<section class="netbox-explorer-content">
<div class="netbox-explorer-pane" data-folder="root" data-parent="" data-title="{% trans "Documents" %}">
{% for node in tree %}
{% include 'netbox_documentation/inc/explorer_folder_tile.html' with node=node %}
{% endfor %}
{% for document in uncategorized %}
{% include 'netbox_documentation/inc/explorer_file_tile.html' with document=document %}
{% endfor %}
</div>
{% for node in tree %}
{% include 'netbox_documentation/inc/explorer_pane.html' with node=node parent='root' %}
{% endfor %}
<div class="netbox-explorer-pane d-none" id="doc-explorer-results"></div>
<p class="text-muted d-none mb-0" id="doc-explorer-nomatch">{% trans "No matches found." %}</p>
</section>
</div>
<div class="card-footer py-1 small text-muted" id="doc-explorer-status"></div>
</div>
<div class="dropdown-menu netbox-explorer-menu" id="doc-explorer-menu" role="menu"></div>
<div class="toast-container position-fixed bottom-0 end-0 p-3" id="doc-explorer-toasts" style="z-index: 1090;"></div>
<form method="post" action="{% url 'plugins:netbox_documentation:document_archive' %}" id="doc-explorer-export" class="d-none">
{% csrf_token %}
<input type="hidden" name="action" value="export">
<input type="hidden" name="categories" value="">
<input type="hidden" name="include_subfolders" value="on">
</form>
{% endif %}
<div class="card" id="doc-tree-view">
<div class="card-body">
{% if tree or uncategorized %}
<ul class="netbox-doc-tree list-unstyled mb-0">
{% for node in tree %}
{% include 'netbox_documentation/inc/document_tree_node.html' with node=node %}
{% endfor %}
{% for document in uncategorized %}
{% include 'netbox_documentation/inc/document_tree_file.html' with document=document %}
{% endfor %}
</ul>
{% else %}
<p class="text-muted mb-0">{% trans "No documents yet." %}</p>
{% endif %}
</div>
</div>
<style>
.netbox-doc-tree { margin: 0; }
.netbox-doc-tree .netbox-doc-tree { margin-left: 1.5rem; margin-top: .35rem; border-left: 1px dashed var(--tblr-border-color, #dee2e6); padding-left: 1rem; }
.netbox-doc-tree-item { margin-bottom: .35rem; }
.netbox-doc-tree-item > details > summary { list-style: none; cursor: pointer; }
.netbox-doc-tree-item > details > summary::-webkit-details-marker { display: none; }
.netbox-doc-tree-item > details > summary::before { content: "\f0142"; font-family: "Material Design Icons"; margin-right: .35rem; display: inline-block; transition: transform .15s ease; }
.netbox-doc-tree-item > details[open] > summary::before { transform: rotate(90deg); }
.netbox-doc-tree-summary { display: flex; align-items: center; gap: .5rem; padding: .25rem .25rem; border-radius: .25rem; }
.netbox-doc-tree-summary:hover { background-color: var(--tblr-bg-surface-secondary, rgba(0,0,0,.03)); }
.netbox-doc-tree-leaf { margin-left: 1.35rem; }
.netbox-doc-tree-empty { margin-left: 1.35rem; font-size: .875rem; }
/* Explorer view */
.netbox-explorer-body { display: flex; min-height: 28rem; }
.netbox-explorer-nav { width: 16rem; flex-shrink: 0; border-right: 1px solid var(--tblr-border-color, #dee2e6); padding: .5rem 0; overflow: auto; max-height: 70vh; }
.netbox-explorer-nav ul ul { padding-left: 1rem; }
.netbox-explorer-nav-row { display: flex; align-items: center; gap: .35rem; padding: .2rem .5rem; cursor: pointer; white-space: nowrap; user-select: none; }
.netbox-explorer-nav-row:hover { background-color: var(--tblr-bg-surface-secondary, rgba(0,0,0,.04)); }
.netbox-explorer-nav-row.active { background-color: rgba(var(--tblr-primary-rgb, 32,107,196), .15); }
.netbox-explorer-twisty { width: 1rem; flex-shrink: 0; display: inline-block; text-align: center; transition: transform .15s ease; }
.netbox-explorer-twisty.open { transform: rotate(90deg); }
.netbox-explorer-content { flex-grow: 1; padding: 1rem; overflow: auto; max-height: 70vh; }
.netbox-explorer-pane { display: grid; grid-template-columns: repeat(auto-fill, minmax(7.5rem, 1fr)); gap: .5rem; align-content: start; }
.netbox-explorer-tile { display: flex; flex-direction: column; align-items: center; text-align: center; gap: .15rem; padding: .5rem .25rem; border: 1px solid transparent; border-radius: .25rem; cursor: pointer; color: inherit; text-decoration: none; user-select: none; }
.netbox-explorer-tile:hover { background-color: rgba(var(--tblr-primary-rgb, 32,107,196), .08); border-color: rgba(var(--tblr-primary-rgb, 32,107,196), .25); text-decoration: none; color: inherit; }
.netbox-explorer-tile:focus { background-color: rgba(var(--tblr-primary-rgb, 32,107,196), .18); border-color: rgba(var(--tblr-primary-rgb, 32,107,196), .4); outline: none; }
.netbox-explorer-icon { font-size: 3.25rem; line-height: 1; }
.netbox-explorer-label { word-break: break-word; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.netbox-explorer-path { font-size: .75rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.netbox-explorer-empty { grid-column: 1 / -1; }
.netbox-explorer-address { display: flex; align-items: center; flex-wrap: wrap; gap: .15rem; border: 1px solid var(--tblr-border-color, #dee2e6); border-radius: .25rem; padding: .15rem .5rem; min-height: 2rem; }
.netbox-explorer-address a { cursor: pointer; }
.netbox-explorer-menu { position: fixed; z-index: 1080; min-width: 14rem; }
.netbox-explorer-menu.show { display: block; }
.netbox-explorer-menu .dropdown-item i { width: 1.25rem; display: inline-block; }
.netbox-explorer-tile.context-target { background-color: rgba(var(--tblr-primary-rgb, 32,107,196), .18); border-color: rgba(var(--tblr-primary-rgb, 32,107,196), .4); }
.netbox-explorer-tile[draggable="true"] { cursor: grab; }
.netbox-explorer-tile.dragging { opacity: .4; }
.netbox-explorer-drop { background-color: rgba(var(--tblr-success-rgb, 47,179,68), .18) !important; outline: 2px dashed rgba(var(--tblr-success-rgb, 47,179,68), .8); outline-offset: -2px; }
@media (max-width: 767px) { .netbox-explorer-nav { display: none; } }
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var T = {
status: '{{ _("{folders} folders, {documents} documents")|escapejs }}',
searchResults: '{{ _("Search results in all folders: ")|escapejs }}',
newFolder: '{{ _("New folder")|escapejs }}',
newDocument: '{{ _("New document")|escapejs }}',
exportFolderZip: '{{ _("Export folder as ZIP")|escapejs }}',
folderDetails: '{{ _("Folder details")|escapejs }}',
refresh: '{{ _("Refresh")|escapejs }}',
open: '{{ _("Open")|escapejs }}',
newSubfolder: '{{ _("New subfolder")|escapejs }}',
newDocumentHere: '{{ _("New document here")|escapejs }}',
renameEdit: '{{ _("Rename / edit")|escapejs }}',
exportZip: '{{ _("Export as ZIP")|escapejs }}',
copyLink: '{{ _("Copy link")|escapejs }}',
delete: '{{ _("Delete")|escapejs }}',
openNewTab: '{{ _("Open in new tab")|escapejs }}',
printPdf: '{{ _("Print / export as PDF")|escapejs }}',
close: '{{ _("Close")|escapejs }}',
emptyFolder: '{{ _("This folder is empty.")|escapejs }}',
unexpectedResponse: '{{ _("Unexpected response from the server ({status}).")|escapejs }}',
moved: '{{ _("“{document}” moved to “{folder}”.")|escapejs }}',
moveFailed: '{{ _("Move failed – no connection to the server.")|escapejs }}'
};
var input = document.getElementById('doc-tree-search');
var explorer = document.getElementById('doc-explorer');
var treeView = document.getElementById('doc-tree-view');
var VIEW_KEY = 'netbox_documentation.view';
var view = 'explorer';
try { view = localStorage.getItem(VIEW_KEY) || 'explorer'; } catch (e) {}
// --- Explorer view ---
var current = 'root', backStack = [];
function pane(id) { return explorer.querySelector('.netbox-explorer-pane[data-folder="' + id + '"]'); }
function navRow(id) { return explorer.querySelector('.netbox-explorer-nav-row[data-folder="' + id + '"]'); }
function toggleNav(row, open) {
var sub = row && row.parentElement.querySelector(':scope > ul');
if (!sub) return;
var show = open === undefined ? sub.classList.contains('d-none') : open;
sub.classList.toggle('d-none', !show);
row.querySelector('.netbox-explorer-twisty').classList.toggle('open', show);
}
function openFolder(id, remember) {
var target = pane(id);
if (!target) return;
if (remember !== false && id !== current) backStack.push(current);
current = id;
explorer.querySelectorAll('.netbox-explorer-pane').forEach(function (p) {
p.classList.toggle('d-none', p !== target);
});
// Address bar (breadcrumb)
var parts = [], p = target;
while (p) { parts.unshift(p); p = p.dataset.parent ? pane(p.dataset.parent) : null; }
var address = document.getElementById('doc-explorer-address');
address.innerHTML = '';
parts.forEach(function (part, i) {
if (i) address.insertAdjacentHTML('beforeend', '<i class="mdi mdi-chevron-right text-muted"></i>');
var a = document.createElement('a');
a.textContent = part.dataset.title;
a.dataset.open = part.dataset.folder;
if (i === 0) a.insertAdjacentHTML('afterbegin', '<i class="mdi mdi-folder-home text-warning"></i> ');
address.appendChild(a);
});
// Navigation pane: highlight current folder and expand its ancestors
explorer.querySelectorAll('.netbox-explorer-nav-row.active').forEach(function (r) { r.classList.remove('active'); });
var row = navRow(id);
if (row) {
row.classList.add('active');
var li = row.parentElement.parentElement.closest('li');
while (li) {
toggleNav(li.querySelector(':scope > .netbox-explorer-nav-row'), true);
li = li.parentElement.closest('li');
}
}
document.getElementById('doc-explorer-up').disabled = !target.dataset.parent;
document.getElementById('doc-explorer-back').disabled = !backStack.length;
var props = document.getElementById('doc-explorer-props');
props.classList.toggle('d-none', !target.dataset.url);
if (target.dataset.url) props.href = target.dataset.url;
updateAddLinks();
applySearch();
}
// Point "Add" / "New folder" at the open folder and return here afterwards.
function updateAddLinks() {
var folder = current === 'root' ? '' : current;
var back = window.location.pathname + (folder ? '?folder=' + folder : '');
[['doc-add-document', 'category'], ['doc-add-folder', 'parent']].forEach(function (cfg) {
var link = document.getElementById(cfg[0]);
if (!link) return;
var params = new URLSearchParams();
if (folder) params.set(cfg[1], folder);
params.set('return_url', back);
link.href = link.dataset.base + '?' + params.toString();
});
if (window.history.replaceState) window.history.replaceState(null, '', back);
}
function goUp() {
var parent = pane(current).dataset.parent;
if (parent) openFolder(parent);
}
function folderPath(p) {
var names = [];
while (p) { names.unshift(p.dataset.title); p = p.dataset.parent ? pane(p.dataset.parent) : null; }
return names.join(' › ');
}
function updateStatus(container, prefix) {
var tiles = container.querySelectorAll('.netbox-explorer-tile:not(.d-none)');
var folders = 0, files = 0;
tiles.forEach(function (t) { if (t.dataset.open) { folders++; } else { files++; } });
document.getElementById('doc-explorer-status').textContent = (prefix || '') + T.status.replace('{folders}', folders).replace('{documents}', files);
document.getElementById('doc-explorer-nomatch').classList.toggle('d-none', tiles.length > 0 || !input.value.trim());
}
// Searches across all folders: matching tiles are copied into a results pane, each labelled with its folder path.
function applySearch() {
if (!explorer || view !== 'explorer') return;
var term = input ? input.value.trim().toLowerCase() : '';
var results = document.getElementById('doc-explorer-results');
results.innerHTML = '';
if (!term) {
results.classList.add('d-none');
pane(current).classList.remove('d-none');
updateStatus(pane(current));
return;
}
explorer.querySelectorAll('.netbox-explorer-pane[data-folder]').forEach(function (p) {
p.classList.add('d-none');
p.querySelectorAll('.netbox-explorer-tile').forEach(function (tile) {
if (tile.dataset.name.indexOf(term) === -1) return;
var copy = tile.cloneNode(true);
copy.classList.remove('d-none');
var where = document.createElement('small');
where.className = 'text-muted netbox-explorer-path';
where.innerHTML = '<i class="mdi mdi-folder-outline"></i> ';
where.appendChild(document.createTextNode(folderPath(p)));
copy.appendChild(where);
results.appendChild(copy);
});
});
results.classList.remove('d-none');
updateStatus(results, T.searchResults);
}
if (explorer) {
explorer.addEventListener('click', function (e) {
var row = e.target.closest('.netbox-explorer-nav-row');
if (row && e.target.closest('.netbox-explorer-twisty')) { toggleNav(row); return; }
if (row) { openFolder(row.dataset.folder); return; }
var target = e.target.closest('.netbox-explorer-address [data-open], .netbox-explorer-tile[data-open]');
if (!target) return;
if (target.closest('#doc-explorer-results')) input.value = '';
openFolder(target.dataset.open);
});
explorer.addEventListener('keydown', function (e) {
var tile = e.target.closest('.netbox-explorer-tile[data-open]');
if (tile && e.key === 'Enter') openFolder(tile.dataset.open);
if (e.key === 'Backspace') { e.preventDefault(); goUp(); }
});
document.getElementById('doc-explorer-up').addEventListener('click', goUp);
document.getElementById('doc-explorer-back').addEventListener('click', function () {
if (backStack.length) openFolder(backStack.pop(), false);
});
var startFolder = new URLSearchParams(window.location.search).get('folder');
openFolder(startFolder && pane(startFolder) ? startFolder : 'root', false);
}
// --- Context menu (right click) ---
var menu = document.getElementById('doc-explorer-menu');
function withReturn(url, extra) {
var params = new URLSearchParams(extra || {});
params.set('return_url', window.location.pathname + window.location.search);
return url + '?' + params.toString();
}
function go(url, newTab) { if (newTab) { window.open(url, '_blank'); } else { window.location.href = url; } }
function folderTile(pk) { return explorer.querySelector('.netbox-explorer-pane[data-folder] .netbox-explorer-tile[data-kind="folder"][data-pk="' + pk + '"]'); }
function exportFolder(pk) {
var form = document.getElementById('doc-explorer-export');
form.elements.categories.value = pk;
form.submit();
}
function copyText(text) {
if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(text); return; }
var area = document.createElement('textarea');
area.value = text;
document.body.appendChild(area);
area.select();
try { document.execCommand('copy'); } catch (e) {}
area.remove();
}
// Menu entries for a folder tile, a document tile or (tile === null) the empty area of the open folder.
function itemsFor(tile) {
var addDoc = document.getElementById('doc-add-document');
var addFolder = document.getElementById('doc-add-folder');
if (!tile) {
var here = pane(current);
return [
addFolder && { icon: 'mdi-folder-plus-outline', label: T.newFolder, run: function () { go(addFolder.href); } },
addDoc && { icon: 'mdi-file-document-plus-outline', label: T.newDocument, run: function () { go(addDoc.href); } },
'-',
here.dataset.parent && { icon: 'mdi-folder-zip-outline', label: T.exportFolderZip, run: function () { exportFolder(current); } },
here.dataset.url && { icon: 'mdi-information-outline', label: T.folderDetails, run: function () { go(here.dataset.url); } },
'-',
{ icon: 'mdi-refresh', label: T.refresh, run: function () { window.location.reload(); } }
];
}
var d = tile.dataset;
if (d.kind === 'folder') {
return [
{ icon: 'mdi-folder-open-outline', label: T.open, bold: true, run: function () { if (input) input.value = ''; openFolder(d.pk); } },
{ icon: 'mdi-information-outline', label: T.folderDetails, run: function () { go(d.url); } },
'-',
addFolder && { icon: 'mdi-folder-plus-outline', label: T.newSubfolder, run: function () { go(withReturn(addFolder.dataset.base, { parent: d.pk })); } },
addDoc && { icon: 'mdi-file-document-plus-outline', label: T.newDocumentHere, run: function () { go(withReturn(addDoc.dataset.base, { category: d.pk })); } },
'-',
d.edit && { icon: 'mdi-rename-outline', label: T.renameEdit, run: function () { go(withReturn(d.edit)); } },
{ icon: 'mdi-folder-zip-outline', label: T.exportZip, run: function () { exportFolder(d.pk); } },
{ icon: 'mdi-link-variant', label: T.copyLink, run: function () { copyText(window.location.origin + window.location.pathname + '?folder=' + d.pk); } },
'-',
d.delete && { icon: 'mdi-trash-can-outline', label: T.delete, danger: true, run: function () { go(withReturn(d.delete)); } }
];
}
var href = tile.getAttribute('href');
return [
{ icon: 'mdi-file-document-outline', label: T.open, bold: true, run: function () { go(href); } },
{ icon: 'mdi-open-in-new', label: T.openNewTab, run: function () { go(href, true); } },
'-',
d.edit && { icon: 'mdi-rename-outline', label: T.renameEdit, run: function () { go(withReturn(d.edit)); } },
{ icon: 'mdi-printer-outline', label: T.printPdf, run: function () { go(d.print, true); } },
{ icon: 'mdi-link-variant', label: T.copyLink, run: function () { copyText(new URL(href, window.location.href).href); } },
'-',
d.delete && { icon: 'mdi-trash-can-outline', label: T.delete, danger: true, run: function () { go(withReturn(d.delete)); } }
];
}
function closeMenu() {
if (!menu) return;
menu.classList.remove('show');
explorer.querySelectorAll('.context-target').forEach(function (t) { t.classList.remove('context-target'); });
}
function showMenu(x, y, tile) {
closeMenu();
menu.innerHTML = '';
itemsFor(tile).forEach(function (item) {
if (!item) return;
var lastIsDivider = !menu.lastElementChild || menu.lastElementChild.classList.contains('dropdown-divider');
if (item === '-') {
if (!lastIsDivider) menu.insertAdjacentHTML('beforeend', '<div class="dropdown-divider"></div>');
return;
}
var b = document.createElement('button');
b.type = 'button';
b.className = 'dropdown-item' + (item.danger ? ' text-danger' : '') + (item.bold ? ' fw-bold' : '');
b.innerHTML = '<i class="mdi ' + item.icon + '"></i> ';
b.appendChild(document.createTextNode(item.label));
b.addEventListener('click', function () { closeMenu(); item.run(); });
menu.appendChild(b);
});
if (menu.lastElementChild && menu.lastElementChild.classList.contains('dropdown-divider')) menu.lastElementChild.remove();
if (tile) tile.classList.add('context-target');
menu.classList.add('show');
// Keep the menu inside the viewport
var r = menu.getBoundingClientRect();
menu.style.left = Math.max(0, Math.min(x, window.innerWidth - r.width - 4)) + 'px';
menu.style.top = Math.max(0, Math.min(y, window.innerHeight - r.height - 4)) + 'px';
var first = menu.querySelector('.dropdown-item');
if (first) first.focus();
}
if (explorer) {
explorer.addEventListener('contextmenu', function (e) {
var tile = e.target.closest('.netbox-explorer-tile');
var row = e.target.closest('.netbox-explorer-nav-row');
if (row) tile = row.dataset.folder === 'root' ? null : folderTile(row.dataset.folder);
if (!tile && !e.target.closest('.netbox-explorer-content, .netbox-explorer-nav')) return;
e.preventDefault();
showMenu(e.clientX, e.clientY, tile);
});
// Context-menu key / Shift+F10 on a focused tile
explorer.addEventListener('keydown', function (e) {
var tile = e.target.closest('.netbox-explorer-tile');
if (!tile || !(e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10'))) return;
e.preventDefault();
var r = tile.getBoundingClientRect();
showMenu(r.left + r.width / 2, r.top + r.height / 2, tile);
});
menu.addEventListener('keydown', function (e) {
var items = Array.prototype.slice.call(menu.querySelectorAll('.dropdown-item'));
var i = items.indexOf(document.activeElement);
if (e.key === 'ArrowDown') { e.preventDefault(); items[(i + 1) % items.length].focus(); }
if (e.key === 'ArrowUp') { e.preventDefault(); items[(i - 1 + items.length) % items.length].focus(); }
});
document.addEventListener('click', function (e) { if (!menu.contains(e.target)) closeMenu(); });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeMenu(); });
window.addEventListener('scroll', closeMenu, true);
window.addEventListener('resize', closeMenu);
}
// --- Drag & drop: move documents between folders ---
function toast(message, ok) {
var box = document.getElementById('doc-explorer-toasts');
var el = document.createElement('div');
el.className = 'toast show align-items-center border-0 text-bg-' + (ok ? 'success' : 'danger');
el.setAttribute('role', 'alert');
el.innerHTML = '<div class="d-flex"><div class="toast-body"></div><button type="button" class="btn-close btn-close-white me-2 m-auto" aria-label="' + T.close + '"></button></div>';
el.querySelector('.toast-body').textContent = message;
el.querySelector('.btn-close').addEventListener('click', function () { el.remove(); });
box.appendChild(el);
setTimeout(function () { el.remove(); }, ok ? 3500 : 7000);
}
// Resolve a drop target element to a folder id ('root' or a pk).
function dropFolder(el) {
var t = el.closest('.netbox-explorer-tile[data-kind="folder"], .netbox-explorer-nav-row, .netbox-explorer-address [data-open]');
if (t) return t.dataset.open || t.dataset.folder;
if (el.closest('.netbox-explorer-content') && !document.getElementById('doc-explorer-results').contains(el) && !(input && input.value.trim())) return current;
return null;
}
function dropHighlight(el) {
return el.closest('.netbox-explorer-tile[data-kind="folder"], .netbox-explorer-nav-row, .netbox-explorer-address [data-open]') || el.closest('.netbox-explorer-content');
}
function originalTile(pk) { return explorer.querySelector('.netbox-explorer-pane[data-folder] .netbox-explorer-tile[data-kind="document"][data-pk="' + pk + '"]'); }
function refreshFolderTile(folderId) {
var f = folderTile(folderId), p = pane(folderId);
if (!p) return;
var count = p.querySelectorAll('.netbox-explorer-tile').length;
var empty = p.querySelector('.netbox-explorer-empty');
if (!count && !empty) p.insertAdjacentHTML('beforeend', '<p class="text-muted netbox-explorer-empty">' + T.emptyFolder + '</p>');
if (count && empty) empty.remove();
if (!f) return;
f.querySelector('small').textContent = count + ' Element(e)';
var icon = f.querySelector('.netbox-explorer-icon');
icon.classList.toggle('mdi-folder', count > 0);
icon.classList.toggle('mdi-folder-outline', count === 0);
}
var dragged = null, lastHighlight = null;
function clearHighlight() {
if (lastHighlight) lastHighlight.classList.remove('netbox-explorer-drop');
lastHighlight = null;
}
function moveDocument(doc, folderId) {
var source = doc.closest('.netbox-explorer-pane[data-folder]').dataset.folder;
if (source === folderId) return;
var body = new FormData();
body.append('category', folderId === 'root' ? '' : folderId);
body.append('csrfmiddlewaretoken', document.querySelector('#doc-explorer-export [name=csrfmiddlewaretoken]').value);
fetch(doc.dataset.move, { method: 'POST', body: body, credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } })
.then(function (r) { return r.json().catch(function () { return { error: T.unexpectedResponse.replace('{status}', r.status) }; }); })
.then(function (data) {
if (data.error) { toast(data.error, false); return; }
pane(folderId).appendChild(doc);
refreshFolderTile(source);
refreshFolderTile(folderId);
treeStale = true;
toast(T.moved.replace('{document}', doc.title).replace('{folder}', pane(folderId).dataset.title), true);
applySearch();
})
.catch(function () { toast(T.moveFailed, false); });
}
if (explorer) {
explorer.addEventListener('dragstart', function (e) {
var tile = e.target.closest && e.target.closest('.netbox-explorer-tile[data-move]');
if (!tile) return;
dragged = originalTile(tile.dataset.pk);
closeMenu();
tile.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', tile.title);
});
explorer.addEventListener('dragend', function (e) {
if (e.target.classList) e.target.classList.remove('dragging');
dragged = null;
clearHighlight();
});
explorer.addEventListener('dragover', function (e) {
if (!dragged) return;
var folderId = dropFolder(e.target);
var el = folderId && dropHighlight(e.target);
if (el !== lastHighlight) clearHighlight();
if (!folderId) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
lastHighlight = el;
el.classList.add('netbox-explorer-drop');
});
explorer.addEventListener('drop', function (e) {
if (!dragged) return;
e.preventDefault();
var folderId = dropFolder(e.target);
clearHighlight();
if (folderId) moveDocument(dragged, folderId);
});
}
// --- View switcher ---
var treeStale = false;
function setView(v) {
if (v === 'tree' && treeStale) {
try { localStorage.setItem(VIEW_KEY, v); } catch (e) {}
window.location.reload();
return;
}
view = explorer ? v : 'tree';
if (explorer) explorer.hidden = view !== 'explorer';
treeView.hidden = view === 'explorer';
document.querySelectorAll('[data-view]').forEach(function (b) {
b.classList.toggle('active', b.dataset.view === view);
});
try { localStorage.setItem(VIEW_KEY, v); } catch (e) {}
applySearch();
}
document.querySelectorAll('[data-view]').forEach(function (b) {
b.addEventListener('click', function () { setView(b.dataset.view); });
});
setView(view);
// --- Tree view search ---
if (!input) return;
input.addEventListener('input', function () {
applySearch();
var term = input.value.trim().toLowerCase();
document.querySelectorAll('.netbox-doc-tree-item').forEach(function (li) {
var match = !term || li.dataset.name.indexOf(term) !== -1;
li.classList.toggle('d-none', !match);
if (match) {
var parent = li.parentElement.closest('.netbox-doc-tree-item');
while (parent) {
parent.classList.remove('d-none');
var details = parent.querySelector(':scope > details');
if (details) details.open = true;
parent = parent.parentElement.closest('.netbox-doc-tree-item');
}
}
});
});
});
</script>
{% endblock %}
@@ -1,24 +1,43 @@
{% extends 'generic/object.html' %}
{% load i18n %}
{% block content %}
<nav aria-label="{% trans "Breadcrumb" %}" class="mb-3">
<ol class="breadcrumb mb-0">
<li class="breadcrumb-item"><a href="{% url 'plugins:netbox_documentation:documentcategory_tree' %}"><i class="mdi mdi-folder-home"></i> {% trans "Folders" %}</a></li>
{% for ancestor in object.ancestors %}
<li class="breadcrumb-item"><a href="{{ ancestor.get_absolute_url }}">{{ ancestor.name }}</a></li>
{% endfor %}
<li class="breadcrumb-item active" aria-current="page">{{ object.name }}</li>
</ol>
</nav>
<div class="row">
<div class="col col-md-4">
{% if object.tenant_group or object.tenant %}
<div class="card mb-3">
<h5 class="card-header">{% trans "Tenancy" %}</h5>
<div class="list-group list-group-flush">
{% if object.tenant_group %}<a class="list-group-item list-group-item-action" href="{{ object.tenant_group.get_absolute_url }}"><i class="mdi mdi-account-group"></i> {{ object.tenant_group }}</a>{% endif %}
{% if object.tenant %}<a class="list-group-item list-group-item-action" href="{{ object.tenant.get_absolute_url }}"><i class="mdi mdi-domain"></i> {{ object.tenant }}</a>{% endif %}
</div>
</div>
{% endif %}
<div class="card">
<h5 class="card-header">Unterordner</h5>
<h5 class="card-header">{% trans "Subfolders" %}</h5>
<div class="list-group list-group-flush">
{% for child in object.children.all %}
<a class="list-group-item list-group-item-action" href="{{ child.get_absolute_url }}"><i class="mdi mdi-folder"></i> {{ child.name }}</a>
{% empty %}<div class="list-group-item text-muted">Keine Unterordner</div>{% endfor %}
{% empty %}<div class="list-group-item text-muted">{% trans "No subfolders" %}</div>{% endfor %}
</div>
</div>
</div>
<div class="col col-md-8">
<div class="card">
<h5 class="card-header">Dokumentationen</h5>
<h5 class="card-header">{% trans "Documents" %}</h5>
<div class="list-group list-group-flush">
{% for document in object.documents.all %}
<a class="list-group-item list-group-item-action" href="{{ document.get_absolute_url }}"><strong>{{ document.title }}</strong>{% if document.summary %}<br><small>{{ document.summary }}</small>{% endif %}</a>
{% empty %}<div class="list-group-item text-muted">Keine Dokumentationen in diesem Ordner</div>{% endfor %}
{% empty %}<div class="list-group-item text-muted">{% trans "No documents in this folder" %}</div>{% endfor %}
</div>
</div>
</div>
@@ -0,0 +1,67 @@
{% extends 'base/layout.html' %}
{% load i18n %}
{% block title %}{% trans "Folders & categories" %}{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col d-flex justify-content-between align-items-center flex-wrap gap-2">
<input type="search" id="folder-tree-search" class="form-control" style="max-width: 20rem;" placeholder="{% trans "Search folders…" %}">
<div class="d-flex gap-2">
{% if perms.netbox_documentation.add_documentcategory %}
<a href="{% url 'plugins:netbox_documentation:documentcategory_add' %}" class="btn btn-success"><i class="mdi mdi-folder-plus"></i> {% trans "Create folder" %}</a>
{% endif %}
<a href="{% url 'plugins:netbox_documentation:documentcategory_list' %}" class="btn btn-outline-secondary"><i class="mdi mdi-format-list-bulleted"></i> {% trans "List view" %}</a>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
{% if tree %}
<ul class="netbox-doc-tree list-unstyled mb-0">
{% for node in tree %}
{% include 'netbox_documentation/inc/category_tree_node.html' with node=node %}
{% endfor %}
</ul>
{% else %}
<p class="text-muted mb-0">{% trans "No folders yet." %}</p>
{% endif %}
</div>
</div>
<style>
.netbox-doc-tree { margin: 0; }
.netbox-doc-tree .netbox-doc-tree { margin-left: 1.5rem; margin-top: .35rem; border-left: 1px dashed var(--tblr-border-color, #dee2e6); padding-left: 1rem; }
.netbox-doc-tree-item { margin-bottom: .35rem; }
.netbox-doc-tree-item > details > summary { list-style: none; cursor: pointer; }
.netbox-doc-tree-item > details > summary::-webkit-details-marker { display: none; }
.netbox-doc-tree-item > details > summary::before { content: "\f0142"; font-family: "Material Design Icons"; margin-right: .35rem; display: inline-block; transition: transform .15s ease; }
.netbox-doc-tree-item > details[open] > summary::before { transform: rotate(90deg); }
.netbox-doc-tree-summary { display: flex; align-items: center; gap: .5rem; padding: .25rem .25rem; border-radius: .25rem; }
.netbox-doc-tree-summary:hover { background-color: var(--tblr-bg-surface-secondary, rgba(0,0,0,.03)); }
.netbox-doc-tree-leaf { margin-left: 1.35rem; }
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var input = document.getElementById('folder-tree-search');
if (!input) return;
input.addEventListener('input', function () {
var term = input.value.trim().toLowerCase();
document.querySelectorAll('.netbox-doc-tree-item').forEach(function (li) {
var match = !term || li.dataset.name.indexOf(term) !== -1;
li.classList.toggle('d-none', !match);
if (match) {
var parent = li.parentElement.closest('.netbox-doc-tree-item');
while (parent) {
parent.classList.remove('d-none');
var details = parent.querySelector(':scope > details');
if (details) details.open = true;
parent = parent.parentElement.closest('.netbox-doc-tree-item');
}
}
});
});
});
</script>
{% endblock %}
@@ -1,7 +1,8 @@
{% extends 'base/layout.html' %}
{% load i18n %}
{% load form_helpers %}
{% block title %}Excel-Importvorschau{% endblock %}
{% block title %}{% trans "Excel import preview" %}{% endblock %}
{% block head %}
{{ block.super }}
@@ -9,7 +10,7 @@
.excel-preview-content { max-height: 32rem; overflow: auto; }
.excel-preview-content table { width: max-content; min-width: 100%; border-collapse: collapse; font-size: .825rem; }
.excel-preview-content th, .excel-preview-content td { min-width: 7rem; max-width: 22rem; padding: .3rem .45rem; border: 1px solid var(--tblr-border-color, #adb5bd); vertical-align: top; overflow-wrap: anywhere; }
.excel-preview-content th { background: var(--tblr-bg-surface-secondary, #f1f3f5); }
.excel-preview-content th:not([style*="background"]) { background: var(--tblr-bg-surface-secondary, #f1f3f5); }
</style>
{% endblock head %}
@@ -17,15 +18,25 @@
<div class="card mb-4">
<div class="card-body">
<div class="d-flex flex-wrap gap-4">
<div><strong>Datei:</strong> {{ batch.original_name }}</div>
<div><strong>Zielordner:</strong> {{ batch.category|default:"Nicht mehr vorhanden" }}</div>
<div><strong>Glätten:</strong> {% if batch.flatten %}Ja{% else %}Nein{% endif %}</div>
<div><strong>{% trans "File" %}:</strong> {{ batch.original_name }}</div>
<div><strong>{% trans "Target folder" %}:</strong> {% if batch.category %}{{ batch.category }}{% else %}{% trans "No longer exists" %}{% endif %}</div>
<div><strong>{% trans "Flatten" %}:</strong> {% if batch.flatten %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</div>
</div>
</div>
</div>
<form method="post">
{% csrf_token %}
{% if overwrite_conflicts %}
<input type="hidden" name="confirm_overwrite" value="1">
<div class="alert alert-warning mx-0" role="alert">
<h3 class="alert-title">{% trans "Update existing documents?" %}</h3>
<p>{% trans "The following documents already exist in the target folder. Their content will be overwritten; existing NetBox assignments are kept:" %}</p>
<ul class="mb-0">
{% for document in overwrite_conflicts %}<li>{{ document.title }}</li>{% endfor %}
</ul>
</div>
{% endif %}
{{ formset.management_form }}
{% if formset.non_form_errors %}<div class="alert alert-danger">{{ formset.non_form_errors }}</div>{% endif %}
@@ -35,22 +46,22 @@
<div class="row align-items-center w-100 g-3">
<div class="col-auto">
{{ item.form.include }}
<label for="{{ item.form.include.id_for_label }}" class="ms-1">Importieren</label>
<label for="{{ item.form.include.id_for_label }}" class="ms-1">{% trans "Import" %}</label>
</div>
<div class="col">
{{ item.form.index }}
<label for="{{ item.form.title.id_for_label }}" class="form-label mb-1">Dokumenttitel</label>
<label for="{{ item.form.title.id_for_label }}" class="form-label mb-1">{% trans "Document title" %}</label>
{{ item.form.title }}
{% for error in item.form.title.errors %}<div class="invalid-feedback d-block">{{ error }}</div>{% endfor %}
</div>
<div class="col-auto text-muted">
{{ item.sheet.images|length }} Bild{{ item.sheet.images|length|pluralize:"er" }}
{% with count=item.sheet.images|length %}{% blocktrans count counter=count %}{{ counter }} image{% plural %}{{ counter }} images{% endblocktrans %}{% endwith %}
</div>
</div>
</div>
<div class="card-body p-0">
<details>
<summary class="p-3 fw-bold" style="cursor:pointer">Vorschau der erzeugten Dokumentation anzeigen</summary>
<summary class="p-3 fw-bold" style="cursor:pointer">{% trans "Show preview of the generated document" %}</summary>
<div class="excel-preview-content border-top p-3 rendered-markdown">
{{ item.preview_html|safe }}
</div>
@@ -61,8 +72,11 @@
<div class="sticky-actions sticky-actions-footer d-print-none" data-sticky-position="full" data-sticky-when="always">
<div class="btn-list">
<button type="submit" name="action" value="cancel" class="btn btn-outline-secondary">Abbrechen</button>
<button type="submit" name="action" value="confirm" class="btn btn-primary"><i class="mdi mdi-file-import"></i> Ausgewählte Arbeitsblätter importieren</button>
<button type="submit" name="action" value="cancel" class="btn btn-outline-secondary">{% trans "Cancel" %}</button>
<button type="submit" name="action" value="confirm" class="btn {% if overwrite_conflicts %}btn-warning{% else %}btn-primary{% endif %}">
<i class="mdi mdi-file-import"></i>
{% if overwrite_conflicts %}{% trans "Overwrite and import" %}{% else %}{% trans "Import selected worksheets" %}{% endif %}
</button>
</div>
</div>
</form>
@@ -0,0 +1,31 @@
{% load i18n %}
<li class="netbox-doc-tree-item" data-name="{{ node.object.name|lower }}">
{% if node.children %}
<details open>
<summary class="netbox-doc-tree-summary">
<i class="mdi mdi-folder text-warning"></i>
<a href="{{ node.object.get_absolute_url }}">{{ node.object.name }}</a>
<span class="badge text-bg-secondary">{{ node.object.document_total }}</span>
{% if node.object.tenant %}<span class="badge text-bg-light"><i class="mdi mdi-domain"></i> {{ node.object.tenant }}</span>{% endif %}
{% if perms.netbox_documentation.change_documentcategory %}
<a href="{% url 'plugins:netbox_documentation:documentcategory_edit' node.object.pk %}" class="btn btn-sm btn-ghost-secondary" title="{% trans "Edit" %}"><i class="mdi mdi-pencil"></i></a>
{% endif %}
</summary>
<ul class="netbox-doc-tree list-unstyled">
{% for child in node.children %}
{% include 'netbox_documentation/inc/category_tree_node.html' with node=child %}
{% endfor %}
</ul>
</details>
{% else %}
<div class="netbox-doc-tree-summary netbox-doc-tree-leaf">
<i class="mdi mdi-folder-outline text-warning"></i>
<a href="{{ node.object.get_absolute_url }}">{{ node.object.name }}</a>
<span class="badge text-bg-secondary">{{ node.object.document_total }}</span>
{% if node.object.tenant %}<span class="badge text-bg-light"><i class="mdi mdi-domain"></i> {{ node.object.tenant }}</span>{% endif %}
{% if perms.netbox_documentation.change_documentcategory %}
<a href="{% url 'plugins:netbox_documentation:documentcategory_edit' node.object.pk %}" class="btn btn-sm btn-ghost-secondary" title="{% trans "Edit" %}"><i class="mdi mdi-pencil"></i></a>
{% endif %}
</div>
{% endif %}
</li>
@@ -0,0 +1,9 @@
{% load i18n %}
<li class="netbox-doc-tree-item netbox-doc-tree-file" data-name="{{ document.title|lower }}">
<div class="netbox-doc-tree-summary netbox-doc-tree-leaf">
<i class="mdi mdi-file-document-outline text-secondary"></i>
<a href="{{ document.get_absolute_url }}">{{ document.title }}</a>
{% if not document.is_published %}<span class="badge text-bg-warning">{% trans "Draft" %}</span>{% endif %}
{% if document.tenant %}<span class="badge text-bg-light"><i class="mdi mdi-domain"></i> {{ document.tenant }}</span>{% endif %}
</div>
</li>
@@ -0,0 +1,21 @@
{% load i18n %}
<li class="netbox-doc-tree-item" data-name="{{ node.object.name|lower }}">
<details open>
<summary class="netbox-doc-tree-summary">
<i class="mdi mdi-folder text-warning"></i>
<a href="{{ node.object.get_absolute_url }}">{{ node.object.name }}</a>
{% if node.object.tenant %}<span class="badge text-bg-light"><i class="mdi mdi-domain"></i> {{ node.object.tenant }}</span>{% endif %}
</summary>
<ul class="netbox-doc-tree list-unstyled">
{% for child in node.children %}
{% include 'netbox_documentation/inc/document_tree_node.html' with node=child %}
{% endfor %}
{% for document in node.documents %}
{% include 'netbox_documentation/inc/document_tree_file.html' with document=document %}
{% endfor %}
{% if not node.children and not node.documents %}
<li class="netbox-doc-tree-empty text-muted">{% trans "Empty" %}</li>
{% endif %}
</ul>
</details>
</li>
@@ -0,0 +1,10 @@
{% load i18n %}
<a class="netbox-explorer-tile" href="{{ document.get_absolute_url }}" data-name="{{ document.title|lower }}" title="{{ document.title }}"
data-kind="document" data-pk="{{ document.pk }}" data-print="{% url 'plugins:netbox_documentation:document_print' pk=document.pk %}"
{% if perms.netbox_documentation.change_document %}data-edit="{% url 'plugins:netbox_documentation:document_edit' pk=document.pk %}" data-move="{% url 'plugins:netbox_documentation:document_move' pk=document.pk %}" draggable="true"{% endif %}
{% if perms.netbox_documentation.delete_document %}data-delete="{% url 'plugins:netbox_documentation:document_delete' pk=document.pk %}"{% endif %}>
<i class="mdi mdi-file-document-outline netbox-explorer-icon text-primary"></i>
<span class="netbox-explorer-label">{{ document.title }}</span>
{% if not document.is_published %}<span class="badge text-bg-warning">{% trans "Draft" %}</span>{% endif %}
{% if document.tenant %}<small class="text-muted text-truncate mw-100"><i class="mdi mdi-domain"></i> {{ document.tenant }}</small>{% endif %}
</a>
@@ -0,0 +1,9 @@
{% load i18n %}
<div class="netbox-explorer-tile" data-open="{{ node.object.pk }}" data-name="{{ node.object.name|lower }}" title="{{ node.object.name }}" tabindex="0"
data-kind="folder" data-pk="{{ node.object.pk }}" data-url="{{ node.object.get_absolute_url }}"
{% if perms.netbox_documentation.change_documentcategory %}data-edit="{% url 'plugins:netbox_documentation:documentcategory_edit' pk=node.object.pk %}"{% endif %}
{% if perms.netbox_documentation.delete_documentcategory %}data-delete="{% url 'plugins:netbox_documentation:documentcategory_delete' pk=node.object.pk %}"{% endif %}>
<i class="mdi {% if node.children or node.documents %}mdi-folder{% else %}mdi-folder-outline{% endif %} netbox-explorer-icon text-warning"></i>
<span class="netbox-explorer-label">{{ node.object.name }}</span>
<small class="text-muted">{% with c=node.children|length d=node.documents|length %}{% with total=c|add:d %}{% blocktrans count counter=total %}{{ counter }} item{% plural %}{{ counter }} items{% endblocktrans %}{% endwith %}{% endwith %}</small>
</div>
@@ -0,0 +1,14 @@
<li>
<div class="netbox-explorer-nav-row" data-folder="{{ node.object.pk }}">
{% if node.children %}<i class="mdi mdi-chevron-right netbox-explorer-twisty"></i>{% else %}<span class="netbox-explorer-twisty"></span>{% endif %}
<i class="mdi mdi-folder text-warning"></i>
<span class="text-truncate">{{ node.object.name }}</span>
</div>
{% if node.children %}
<ul class="list-unstyled d-none">
{% for child in node.children %}
{% include 'netbox_documentation/inc/explorer_nav_node.html' with node=child %}
{% endfor %}
</ul>
{% endif %}
</li>
@@ -0,0 +1,13 @@
{% load i18n %}
<div class="netbox-explorer-pane d-none" data-folder="{{ node.object.pk }}" data-parent="{{ parent|default:'root' }}" data-title="{{ node.object.name }}" data-url="{{ node.object.get_absolute_url }}">
{% for child in node.children %}
{% include 'netbox_documentation/inc/explorer_folder_tile.html' with node=child %}
{% endfor %}
{% for document in node.documents %}
{% include 'netbox_documentation/inc/explorer_file_tile.html' with document=document %}
{% endfor %}
{% if not node.children and not node.documents %}<p class="text-muted netbox-explorer-empty">{% trans "This folder is empty." %}</p>{% endif %}
</div>
{% for child in node.children %}
{% include 'netbox_documentation/inc/explorer_pane.html' with node=child parent=node.object.pk %}
{% endfor %}
@@ -1,11 +1,12 @@
{% load i18n %}
<div class="card">
<h5 class="card-header"><i class="mdi mdi-book-open-page-variant"></i> Dokumentation</h5>
<h5 class="card-header"><i class="mdi mdi-book-open-page-variant"></i> {% trans "Documentation" %}</h5>
<div class="list-group list-group-flush">
{% for assignment in documentation_assignments %}
<a class="list-group-item list-group-item-action" href="{{ assignment.document.get_absolute_url }}">
<strong>{{ assignment.document.title }}</strong>{% if assignment.note %}<br><small>{{ assignment.note }}</small>{% endif %}
</a>
{% empty %}<div class="list-group-item text-muted">Keine Dokumentation zugeordnet.</div>{% endfor %}
{% empty %}<div class="list-group-item text-muted">{% trans "No documents assigned." %}</div>{% endfor %}
</div>
{% if perms.netbox_documentation.add_documentassignment %}<div class="card-footer"><a href="{% url 'plugins:netbox_documentation:documentassignment_add' %}?assigned_object_type={{ content_type.pk }}&assigned_object={{ object.pk }}" class="btn btn-sm btn-primary"><i class="mdi mdi-link-plus"></i> Zuordnen</a></div>{% endif %}
{% if perms.netbox_documentation.add_documentassignment %}<div class="card-footer"><a href="{% url 'plugins:netbox_documentation:documentassignment_add' %}?assigned_object_type={{ content_type.pk }}&assigned_object={{ object.pk }}" class="btn btn-sm btn-primary"><i class="mdi mdi-link-plus"></i> {% trans "Assign" %}</a></div>{% endif %}
</div>
+4 -1
View File
@@ -4,7 +4,8 @@ from . import models, views
urlpatterns = (
path("editor-assets/<path:asset_path>", views.EditorAssetView.as_view(), name="editor_asset"),
path("", views.DocumentListView.as_view(), name="document_list"),
path("", views.DocumentTreeView.as_view(), name="document_tree"),
path("list/", views.DocumentListView.as_view(), name="document_list"),
path("documents/add/", views.DocumentEditView.as_view(), name="document_add"),
path("documents/import/", views.DocumentImportView.as_view(), name="document_import"),
path("documents/import/", views.DocumentImportView.as_view(), name="document_bulk_import"),
@@ -15,6 +16,7 @@ urlpatterns = (
path("documents/<int:pk>/print/", views.DocumentPrintView.as_view(), name="document_print"),
path("documents/<int:pk>/edit/", views.DocumentEditView.as_view(), name="document_edit"),
path("documents/<int:pk>/media-upload/", views.DocumentMediaUploadView.as_view(), name="document_media_upload"),
path("documents/<int:pk>/move/", views.DocumentMoveView.as_view(), name="document_move"),
path("documents/<int:pk>/delete/", views.DocumentDeleteView.as_view(), name="document_delete"),
path("documents/<int:pk>/changelog/", ObjectChangeLogView.as_view(), name="document_changelog", kwargs={"model": models.Document}),
path("assignments/", views.AssignmentListView.as_view(), name="documentassignment_list"),
@@ -24,6 +26,7 @@ urlpatterns = (
path("assignments/<int:pk>/edit/", views.AssignmentEditView.as_view(), name="documentassignment_edit"),
path("assignments/<int:pk>/delete/", views.AssignmentDeleteView.as_view(), name="documentassignment_delete"),
path("folders/", views.DocumentCategoryListView.as_view(), name="documentcategory_list"),
path("folders/tree/", views.DocumentCategoryTreeView.as_view(), name="documentcategory_tree"),
path("folders/add/", views.DocumentCategoryEditView.as_view(), name="documentcategory_add"),
path("folders/import/", views.DocumentImportView.as_view(), name="documentcategory_bulk_import"),
path("folders/delete/", views.DocumentCategoryBulkDeleteView.as_view(), name="documentcategory_bulk_delete"),
+264 -68
View File
@@ -1,15 +1,18 @@
from pathlib import Path
from datetime import timedelta
from html import escape
import mimetypes
import tinymce
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import PermissionDenied
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.db.models import Count, Q
from django.http import FileResponse, Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.text import slugify
from django.utils.translation import gettext as _, ngettext
from django.utils import timezone
from django.views import View
from netbox.views import generic
@@ -28,6 +31,21 @@ from .models import (
from .tables import DocumentTable, AssignmentTable, DocumentCategoryTable
def _active_tenant_ids(request):
"""Tenant IDs of the globally selected tenant/tenant-group (netbox-utilities), if any.
Our tree views build their querysets by hand rather than through a NetBoxModelFilterSet,
so they don't pick up the tenant_id/tenant_group_id GET param that plugin's middleware
injects for FilterSet-based views. Read its public scope API directly instead.
"""
try:
from netbox_utilities.tenant_scope import active_tenant_scope
except ImportError:
return None
scope = active_tenant_scope.get()
return scope.tenant_ids if scope else None
class EditorAssetView(View):
"""Serve the bundled editor assets when NetBox's static proxy is unavailable."""
@@ -44,14 +62,51 @@ class EditorAssetView(View):
class DocumentListView(generic.ObjectListView):
queryset = Document.objects.prefetch_related("assignments")
queryset = Document.objects.select_related("category", "tenant_group", "tenant").prefetch_related("assignments")
table = DocumentTable
filterset = DocumentFilterSet
actions = (AddObject, BulkImport, BulkDelete)
class DocumentTreeView(PermissionRequiredMixin, View):
"""Windows-Explorer/Nextcloud-style folder browser: categories as folders, documents as files."""
permission_required = "netbox_documentation.view_document"
template_name = "netbox_documentation/document_tree.html"
def get(self, request):
tenant_ids = _active_tenant_ids(request)
category_qs = DocumentCategory.objects.restrict(request.user, "view").select_related("tenant_group", "tenant")
document_qs = Document.objects.restrict(request.user, "view").select_related("category", "tenant_group", "tenant")
if tenant_ids is not None:
category_qs = category_qs.filter(tenant_id__in=tenant_ids)
document_qs = document_qs.filter(tenant_id__in=tenant_ids)
categories = list(category_qs.order_by("name"))
documents = list(document_qs.order_by("title"))
nodes = {category.pk: {"object": category, "children": [], "documents": []} for category in categories}
roots = []
for category in categories:
node = nodes[category.pk]
parent_node = nodes.get(category.parent_id)
(parent_node["children"] if parent_node else roots).append(node)
uncategorized = []
for document in documents:
node = nodes.get(document.category_id)
(node["documents"] if node else uncategorized).append(document)
return render(request, self.template_name, {
"tree": roots,
"uncategorized": uncategorized,
"document_count": len(documents),
})
class DocumentView(generic.ObjectView):
queryset = Document.objects.prefetch_related("assignments", "attachments")
queryset = Document.objects.select_related("category", "tenant_group", "tenant").prefetch_related("assignments", "attachments")
class DocumentPrintView(PermissionRequiredMixin, View):
@@ -72,6 +127,30 @@ class DocumentEditView(generic.ObjectEditView):
template_name = "netbox_documentation/document_edit.html"
class DocumentMoveView(PermissionRequiredMixin, View):
"""Move a document into any other folder (drag & drop in the Explorer). Only the folder changes, never the tenant."""
permission_required = "netbox_documentation.change_document"
def post(self, request, pk):
document = get_object_or_404(Document.objects.restrict(request.user, "change"), pk=pk)
category_id = request.POST.get("category") or None
category = None
if category_id is not None:
category = DocumentCategory.objects.restrict(request.user, "view").filter(pk=category_id).first()
if category is None:
return JsonResponse({"error": _("The target folder does not exist.")}, status=404)
if document.category_id != (category.pk if category else None):
document.snapshot()
document.category = category
try:
document.full_clean()
except ValidationError as error:
return JsonResponse({"error": " ".join(error.messages)}, status=400)
document.save()
return JsonResponse({"ok": True, "category": category.pk if category else None})
class DocumentDeleteView(generic.ObjectDeleteView):
queryset = Document.objects.all()
@@ -83,14 +162,43 @@ class DocumentBulkDeleteView(generic.BulkDeleteView):
class DocumentCategoryListView(generic.ObjectListView):
queryset = DocumentCategory.objects.select_related("parent").prefetch_related("documents")
queryset = DocumentCategory.objects.select_related("parent", "tenant_group", "tenant").prefetch_related("documents")
table = DocumentCategoryTable
filterset = DocumentCategoryFilterSet
actions = (AddObject, BulkImport, BulkDelete)
class DocumentCategoryTreeView(PermissionRequiredMixin, View):
"""Nextcloud/Bookstack-style nested folder browser for document categories."""
permission_required = "netbox_documentation.view_documentcategory"
template_name = "netbox_documentation/documentcategory_tree.html"
def get(self, request):
tenant_ids = _active_tenant_ids(request)
category_qs = (
DocumentCategory.objects.restrict(request.user, "view")
.select_related("tenant_group", "tenant")
.annotate(document_total=Count("documents", distinct=True))
)
if tenant_ids is not None:
category_qs = category_qs.filter(tenant_id__in=tenant_ids)
categories = list(category_qs.order_by("name"))
nodes = {category.pk: {"object": category, "children": []} for category in categories}
roots = []
for category in categories:
node = nodes[category.pk]
parent_node = nodes.get(category.parent_id)
(parent_node["children"] if parent_node else roots).append(node)
return render(request, self.template_name, {"tree": roots, "category_count": len(categories)})
class DocumentCategoryView(generic.ObjectView):
queryset = DocumentCategory.objects.prefetch_related("children", "documents")
queryset = DocumentCategory.objects.select_related("parent", "tenant_group", "tenant").prefetch_related(
"parent__parent", "children", "documents",
)
class DocumentCategoryEditView(generic.ObjectEditView):
@@ -148,7 +256,7 @@ class DocumentImportView(PermissionRequiredMixin, View):
result = import_document(upload, flatten_excel=form.cleaned_data.get("flatten_excel_tables", False))
except (ImportFailure, Exception) as exc:
# Known conversion/library errors are presented without exposing a traceback.
form.add_error("file", f"Import fehlgeschlagen: {exc}")
form.add_error("file", _("Import failed: %(error)s") % {"error": exc})
return render(request, self.template_name, {"form": form})
with transaction.atomic():
document = form.cleaned_data.get("document")
@@ -162,13 +270,19 @@ class DocumentImportView(PermissionRequiredMixin, View):
document.save()
else:
title = form.cleaned_data.get("title") or Path(upload.name).stem
base_slug = slugify(title)[:180] or "dokumentation"
base_slug = slugify(title)[:180] or "document"
slug = base_slug
counter = 2
while Document.objects.filter(slug=slug).exists():
slug = f"{base_slug}-{counter}"
counter += 1
document = Document.objects.create(title=title, slug=slug, body=result.markdown, body_format="markdown")
category = form.cleaned_data.get("category")
document = Document.objects.create(
title=title, slug=slug, body=result.markdown, body_format=result.body_format,
category=category,
tenant_group=category.tenant_group if category else None,
tenant=category.tenant if category else None,
)
keep = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("keep_imported_file", True)
if keep:
upload.seek(0)
@@ -176,14 +290,17 @@ class DocumentImportView(PermissionRequiredMixin, View):
original_name=upload.name, content_type=upload.content_type or "", size=upload.size)
for warning in result.warnings:
messages.warning(request, warning)
messages.success(request, f"{upload.name} wurde importiert.")
messages.success(request, _("%(name)s was imported.") % {"name": upload.name})
return redirect(document)
def _import_excel_sheets(self, request, form, upload):
try:
sheets = import_excel_sheets(upload, flatten=form.cleaned_data.get("flatten_excel_tables", False))
sheets = import_excel_sheets(
upload, flatten=form.cleaned_data.get("flatten_excel_tables", False),
metadata_only=True, include_image_data=False,
)
except (ImportFailure, Exception) as exc:
form.add_error("file", f"Excel-Mehrblattimport fehlgeschlagen: {exc}")
form.add_error("file", _("Excel multi-sheet import failed: %(error)s") % {"error": exc})
return render(request, self.template_name, {"form": form})
# Remove abandoned previews owned by this user before creating a new one.
stale = ExcelImportPreview.objects.filter(created__lt=timezone.now() - timedelta(hours=24))
@@ -195,7 +312,10 @@ class DocumentImportView(PermissionRequiredMixin, View):
user=request.user, category=form.cleaned_data["category"], file=upload,
original_name=upload.name, content_type=upload.content_type or "",
flatten=form.cleaned_data.get("flatten_excel_tables", False),
sheet_metadata=[{"title": sheet.title, "image_count": len(sheet.images)} for sheet in sheets],
sheet_metadata=[{
"title": sheet.title, "image_count": len(sheet.images),
"source_index": sheet.source_index,
} for sheet in sheets],
)
return redirect("plugins:netbox_documentation:excel_import_preview", token=preview.pk)
@@ -207,42 +327,60 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
def get_preview(self, request, token):
return get_object_or_404(ExcelImportPreview, pk=token, user=request.user)
def read_sheets(self, preview):
def read_sheets(self, preview, *, for_preview=False, selected_indexes=None):
preview.file.open("rb")
try:
return import_excel_sheets(preview.file, flatten=preview.flatten)
return import_excel_sheets(
preview.file, flatten=preview.flatten,
preview_max_rows=100 if for_preview else None,
include_image_data=not for_preview,
selected_indexes=selected_indexes,
)
finally:
preview.file.close()
def render_preview(self, request, preview, sheets, formset):
def render_preview(self, request, preview, sheets, formset, overwrite_conflicts=None):
items = []
for form, sheet in zip(formset.forms, sheets):
sample = sheet.markdown
if sheet.images:
sample += f"\n\n## Bilder\n\n_{len(sheet.images)} eingebettete Bilder werden beim Import angefügt._"
image_notice = ngettext(
"%(count)s embedded image will be attached on import.",
"%(count)s embedded images will be attached on import.",
len(sheet.images),
) % {"count": len(sheet.images)}
images_heading = _("Images")
if sheet.body_format == "html":
sample += f"\n<h2>{escape(images_heading)}</h2><p><em>{escape(image_notice)}</em></p>"
else:
sample += f"\n\n## {images_heading}\n\n_{image_notice}_"
truncated = len(sample) > 100000
if truncated:
sample = sample[:100000] + "\n\n_… Vorschau gekürzt …_"
preview_document = Document(body=sample, body_format="markdown")
notice = _("… preview truncated …")
sample = sample[:100000] + (
f"<p><em>{notice}</em></p>" if sheet.body_format == "html" else f"\n\n_{notice}_"
)
preview_document = Document(body=sample, body_format=sheet.body_format)
items.append({
"form": form, "sheet": sheet,
"preview_html": preview_document.rendered_body(), "truncated": truncated,
})
return render(request, self.template_name, {
"batch": preview, "formset": formset, "items": items,
"overwrite_conflicts": overwrite_conflicts or [],
})
def get(self, request, token):
preview = self.get_preview(request, token)
if preview.created < timezone.now() - timedelta(hours=24):
self.delete_preview(preview)
messages.error(request, "Diese Importvorschau ist abgelaufen. Bitte die Exceldatei erneut hochladen.")
messages.error(request, _("This import preview has expired. Please upload the Excel file again."))
return redirect("plugins:netbox_documentation:document_import")
try:
sheets = self.read_sheets(preview)
sheets = self.read_sheets(preview, for_preview=True)
except (ImportFailure, Exception) as exc:
self.delete_preview(preview)
messages.error(request, f"Die Excel-Vorschau konnte nicht erzeugt werden: {exc}")
messages.error(request, _("The Excel preview could not be created: %(error)s") % {"error": exc})
return redirect("plugins:netbox_documentation:document_import")
initial = [{"include": True, "index": index, "title": sheet.title} for index, sheet in enumerate(sheets)]
return self.render_preview(request, preview, sheets, ExcelSheetSelectionFormSet(initial=initial))
@@ -251,58 +389,101 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
preview = self.get_preview(request, token)
if request.POST.get("action") == "cancel":
self.delete_preview(preview)
messages.info(request, "Excel-Import wurde abgebrochen.")
return redirect("plugins:netbox_documentation:document_import")
try:
sheets = self.read_sheets(preview)
except (ImportFailure, Exception) as exc:
self.delete_preview(preview)
messages.error(request, f"Die Exceldatei konnte nicht erneut gelesen werden: {exc}")
messages.info(request, _("Excel import was cancelled."))
return redirect("plugins:netbox_documentation:document_import")
formset = ExcelSheetSelectionFormSet(request.POST)
if not formset.is_valid():
return self.render_preview(request, preview, sheets, formset)
try:
preview_sheets = self.read_sheets(preview, for_preview=True)
except (ImportFailure, Exception) as exc:
self.delete_preview(preview)
messages.error(request, _("The Excel file could not be read again: %(error)s") % {"error": exc})
return redirect("plugins:netbox_documentation:document_import")
return self.render_preview(request, preview, preview_sheets, formset)
if not preview.category:
self.delete_preview(preview)
messages.error(request, "Der gewählte Zielordner existiert nicht mehr. Bitte den Import erneut starten.")
messages.error(request, _("The selected target folder no longer exists. Please start the import again."))
return redirect("plugins:netbox_documentation:document_import")
selections = {}
for form in formset.forms:
data = form.cleaned_data
if data.get("include"):
if data["index"] < 0 or data["index"] >= len(sheets):
if data["index"] < 0 or data["index"] >= len(preview.sheet_metadata):
raise PermissionDenied
selections[data["index"]] = data["title"].strip()
result = self.create_documents(preview, sheets, selections)
metadata = preview.sheet_metadata[data["index"]]
source_index = metadata.get("source_index", data["index"])
selections[source_index] = data["title"].strip()
title_query = Q()
for title in selections.values():
title_query |= Q(title__iexact=title)
conflicts = list(Document.objects.filter(
title_query, category=preview.category,
).order_by("title"))
if conflicts:
allowed_ids = set(Document.objects.restrict(request.user, "change").filter(
pk__in=[document.pk for document in conflicts]
).values_list("pk", flat=True))
if any(document.pk not in allowed_ids for document in conflicts):
messages.error(request, _("You are not allowed to update at least one document with the same name."))
return redirect("plugins:netbox_documentation:excel_import_preview", token=preview.pk)
if request.POST.get("confirm_overwrite") != "1":
try:
preview_sheets = self.read_sheets(preview, for_preview=True)
except (ImportFailure, Exception) as exc:
messages.error(request, _("The confirmation could not be displayed: %(error)s") % {"error": exc})
return redirect("plugins:netbox_documentation:excel_import_preview", token=preview.pk)
return self.render_preview(
request, preview, preview_sheets, formset,
overwrite_conflicts=conflicts,
)
try:
selected_sheets = self.read_sheets(preview, selected_indexes=selections)
except (ImportFailure, Exception) as exc:
messages.error(request, _("The selected Excel sheets could not be imported: %(error)s") % {"error": exc})
return redirect("plugins:netbox_documentation:excel_import_preview", token=preview.pk)
sheets_by_index = {sheet.source_index: sheet for sheet in selected_sheets}
result = self.create_documents(preview, sheets_by_index, selections)
self.delete_preview(preview)
messages.success(request, (
f"{result['documents']} Arbeitsblätter als Dokumentationen in „{result['category']}“ importiert; "
f"{result['images']} Bilder übernommen."
))
messages.success(request, _(
"%(documents)s worksheets processed (%(created)s new, %(updated)s updated) "
"in “%(category)s”; %(images)s images imported."
) % result)
return redirect("plugins:netbox_documentation:document_list")
@staticmethod
@transaction.atomic
def create_documents(preview, sheets, selections):
from django.core.files.base import ContentFile
preview.file.open("rb")
try:
original_content = preview.file.read()
finally:
preview.file.close()
created_documents, image_count = [], 0
created_documents, image_count, created_count, updated_count = [], 0, 0, 0
for index, title in selections.items():
sheet = sheets[index]
base_slug = slugify(title)[:180] or "arbeitsblatt"
document_slug, counter = base_slug, 2
while Document.objects.filter(slug=document_slug).exists():
document_slug = f"{base_slug[:190-len(str(counter))]}-{counter}"
counter += 1
document = Document.objects.create(
title=title[:200], slug=document_slug, body=sheet.markdown,
body_format="markdown", category=preview.category,
summary=f"Importiert aus {preview.original_name}",
)
document = Document.objects.select_for_update().filter(
category=preview.category, title__iexact=title,
).order_by("pk").first()
if document:
document.title = title[:200]
document.body = sheet.markdown
document.body_format = sheet.body_format
document.summary = _("Imported from %(name)s") % {"name": preview.original_name}
document.tenant_group = preview.category.tenant_group
document.tenant = preview.category.tenant
document.save(update_fields=(
"title", "body", "body_format", "summary", "tenant_group", "tenant", "last_updated",
))
updated_count += 1
else:
base_slug = slugify(title)[:180] or "worksheet"
document_slug, counter = base_slug, 2
while Document.objects.filter(slug=document_slug).exists():
document_slug = f"{base_slug[:190-len(str(counter))]}-{counter}"
counter += 1
document = Document.objects.create(
title=title[:200], slug=document_slug, body=sheet.markdown,
body_format=sheet.body_format, category=preview.category,
tenant_group=preview.category.tenant_group, tenant=preview.category.tenant,
summary=_("Imported from %(name)s") % {"name": preview.original_name},
)
created_count += 1
if sheet.images:
image_lines = []
for image in sheet.images:
@@ -313,20 +494,35 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
attachment.file.save(image.name, ContentFile(image.content), save=False)
attachment.save()
location = f" ({image.cell})" if image.cell else ""
image_lines.append(f"![{image.name}{location}]({attachment.file.url})")
document.body += "\n\n## Bilder\n\n" + "\n\n".join(image_lines)
if document.body_format == "html":
image_lines.append(
f'<p><img src="{escape(attachment.file.url)}" alt="{escape(image.name + location)}"></p>'
)
else:
image_lines.append(f"![{image.name}{location}]({attachment.file.url})")
if document.body_format == "html":
document.body += f"\n<h2>{escape(_('Images'))}</h2>\n" + "\n".join(image_lines)
else:
document.body += f"\n\n## {_('Images')}\n\n" + "\n\n".join(image_lines)
document.save(update_fields=("body", "last_updated"))
image_count += len(sheet.images)
created_documents.append(document)
if settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("keep_imported_file", True):
for document in created_documents:
preview.file.open("rb")
attachment = DocumentAttachment(
document=document, original_name=preview.original_name,
content_type=preview.content_type, size=len(original_content),
content_type=preview.content_type, size=preview.file.size,
)
attachment.file.save(preview.original_name, ContentFile(original_content), save=False)
attachment.save()
return {"documents": len(created_documents), "images": image_count, "category": preview.category}
try:
attachment.file.save(preview.original_name, preview.file, save=False)
attachment.save()
finally:
preview.file.close()
return {
"documents": len(created_documents), "created": created_count,
"updated": updated_count, "images": image_count, "category": preview.category,
}
@staticmethod
def delete_preview(preview):
@@ -341,20 +537,20 @@ class DocumentMediaUploadView(PermissionRequiredMixin, View):
document = get_object_or_404(Document.objects.restrict(request.user, "change"), pk=pk)
upload = request.FILES.get("file")
if not upload:
return JsonResponse({"error": "Keine Datei empfangen."}, status=400)
return JsonResponse({"error": _("No file received.")}, status=400)
limit = settings.PLUGINS_CONFIG.get("netbox_documentation", {}).get("max_import_size_mb", 25)
if upload.size > limit * 1024 * 1024:
return JsonResponse({"error": f"Die Datei ist größer als {limit} MB."}, status=400)
return JsonResponse({"error": _("The file is larger than %(limit)s MB.") % {"limit": limit}}, status=400)
allowed = {"image/jpeg", "image/png", "image/gif", "image/webp"}
if upload.content_type not in allowed:
return JsonResponse({"error": "Im Editor sind JPEG, PNG, GIF und WebP erlaubt."}, status=400)
return JsonResponse({"error": _("The editor accepts JPEG, PNG, GIF and WebP.")}, status=400)
try:
from PIL import Image
image = Image.open(upload)
image.verify()
upload.seek(0)
except Exception:
return JsonResponse({"error": "Die hochgeladene Datei ist kein gültiges Bild."}, status=400)
return JsonResponse({"error": _("The uploaded file is not a valid image.")}, status=400)
attachment = DocumentAttachment.objects.create(
document=document, file=upload, original_name=upload.name,
content_type=upload.content_type or "", size=upload.size,
@@ -388,7 +584,7 @@ class DocumentArchiveView(View):
form.cleaned_data["categories"], form.cleaned_data["include_subfolders"], request.user
)
if not documents.exists():
form.add_error("categories", "Die ausgewählten Ordner enthalten keine exportierbaren Dokumentationen.")
form.add_error("categories", _("The selected folders contain no exportable documents."))
return self._render(request, export_form=form)
stream = export_documents(documents)
response = FileResponse(stream, content_type="application/zip")
@@ -413,10 +609,10 @@ class DocumentArchiveView(View):
except ArchiveFailure as exc:
form.add_error("archive", str(exc))
return self._render(request, import_form=form)
messages.success(request, (
f"Archiv importiert: {result['created']} erstellt, {result['updated']} aktualisiert."
))
messages.success(request, _(
"Archive imported: %(created)s created, %(updated)s updated."
) % result)
if result["skipped_assignments"]:
messages.warning(request, f"{result['skipped_assignments']} nicht verfügbare Objektzuordnungen wurden übersprungen.")
messages.warning(request, _("%(skipped)s unavailable object assignments were skipped.") % {"skipped": result["skipped_assignments"]})
return redirect("plugins:netbox_documentation:document_list")
return self._render(request)
+8 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "netbox-documentation"
version = "0.7.4"
version = "0.12.1"
description = "Integrated Markdown wiki and office document importer for NetBox"
readme = "README.md"
requires-python = ">=3.10"
@@ -15,6 +15,7 @@ dependencies = [
"pypdf>=5,<7",
"tabulate>=0.9,<1",
"bleach[css]>=6.2,<7",
"Pygments>=2.15,<3",
"markdown>=3.7,<4",
"django-tinymce>=5,<6",
"pillow>=10,<13",
@@ -27,7 +28,12 @@ test = ["pytest>=8", "pytest-django>=4.9"]
include = ["netbox_documentation*"]
[tool.setuptools.package-data]
netbox_documentation = ["templates/**/*.html", "static/**/*"]
netbox_documentation = [
"templates/**/*.html",
"static/**/*",
"locale/*/LC_MESSAGES/*.po",
"locale/*/LC_MESSAGES/*.mo",
]
[tool.pytest.ini_options]
python_files = ["test_*.py"]
+7
View File
@@ -0,0 +1,7 @@
import django
from django.conf import settings
# The importer tests load modules without NetBox; gettext still needs configured settings.
if not settings.configured:
settings.configure(USE_I18N=True, LANGUAGE_CODE="en")
django.setup()
+48
View File
@@ -0,0 +1,48 @@
import base64
from io import BytesIO
import importlib.util
from pathlib import Path
import sys
from PIL import Image
spec = importlib.util.spec_from_file_location(
"documentation_embedded_images",
Path(__file__).parents[1] / "netbox_documentation" / "embedded_images.py",
)
embedded = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = embedded
spec.loader.exec_module(embedded)
def image_data_url():
stream = BytesIO()
Image.new("RGB", (2, 2), "red").save(stream, format="PNG")
return "data:image/png;base64," + base64.b64encode(stream.getvalue()).decode()
def test_embedded_image_is_replaced_with_stored_url():
html = f'<p><img alt="Test" src="{image_data_url()}"></p>'
stored = []
def store(mime, content):
stored.append((mime, content))
return "/media/documentation/bild.png"
result = embedded.store_embedded_images(html, 1024 * 1024, store)
assert 'src="/media/documentation/bild.png"' in result
assert "data:image/" not in result
assert stored[0][0] == "image/png"
assert stored[0][1]
def test_embedded_images_respect_total_size_limit():
html = f'<img src="{image_data_url()}">'
try:
embedded.validate_embedded_images(html, 1)
except embedded.EmbeddedImageError as exc:
assert "total size" in str(exc)
else:
raise AssertionError("size limit was not applied")
+30
View File
@@ -0,0 +1,30 @@
import importlib.util
from pathlib import Path
import sys
spec = importlib.util.spec_from_file_location(
"documentation_highlighting",
Path(__file__).parents[1] / "netbox_documentation" / "highlighting.py",
)
highlighting = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = highlighting
spec.loader.exec_module(highlighting)
def test_highlights_markdown_fence_with_language():
result = highlighting.highlight_code_blocks('<pre><code class="language-python">def f():\n return 1\n</code></pre>')
assert 'class="doc-hl" data-lang="Python"' in result
assert '<span class="k">def</span>' in result
def test_highlights_tinymce_code_sample_and_keeps_escaping():
result = highlighting.highlight_code_blocks('<pre class="language-markup"><code>&lt;b onclick="x"&gt;hi&lt;/b&gt;</code></pre>')
assert 'data-lang="HTML"' in result
assert "<b" not in result.replace("<span", "")
assert "&lt;" in result
def test_plain_text_and_unknown_language_stay_untouched():
for block in ('<pre class="language-none">interface Gi0/1</pre>', '<pre><code class="language-unknownlang">x</code></pre>'):
assert highlighting.highlight_code_blocks(block) == block
+152 -6
View File
@@ -5,7 +5,8 @@ import sys
import pytest
from openpyxl import Workbook
from openpyxl.worksheet.table import Table
from openpyxl.styles import PatternFill, Font
from openpyxl.worksheet.table import Table, TableStyleInfo
spec = importlib.util.spec_from_file_location(
@@ -39,10 +40,54 @@ def test_xlsx_imports_sheets_as_tables():
stream = BytesIO()
workbook.save(stream)
result = import_document(Upload(stream.getvalue(), "server.xlsx"))
assert "## Server" in result.markdown
assert "<h2>Server</h2>" in result.markdown
assert result.body_format == "html"
assert "web01" in result.markdown
def test_xlsx_preserves_cell_fill_and_font_colors_as_html():
workbook = Workbook()
sheet = workbook.active
sheet["A1"] = "Standort"
sheet["A1"].fill = PatternFill(fill_type="solid", fgColor="A5BF60")
sheet["A1"].font = Font(color="FFFFFF", bold=True)
sheet["A2"] = "Verwaltung"
sheet["A2"].fill = PatternFill(fill_type="solid", fgColor="EAF0DC")
stream = BytesIO()
workbook.save(stream)
result = import_document(Upload(stream.getvalue(), "farben.xlsx"))
assert result.body_format == "html"
assert "background-color: #a5bf60" in result.markdown
assert "color: #ffffff" in result.markdown
assert "font-weight: bold" in result.markdown
assert "background-color: #eaf0dc" in result.markdown
def test_xlsx_renders_builtin_excel_table_style_colors_in_preview_html():
workbook = Workbook()
sheet = workbook.active
sheet.append(["Standort", "Adresse"])
sheet.append(["Verwaltung", "10.1.2.17"])
sheet.append(["Büro", "10.1.2.18"])
table = Table(displayName="Standorte", ref="A1:B3")
table.tableStyleInfo = TableStyleInfo(
name="TableStyleMedium4", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=False,
)
sheet.add_table(table)
stream = BytesIO()
workbook.save(stream)
result = import_document(Upload(stream.getvalue(), "tabelle.xlsx"))
assert result.body_format == "html"
assert "Standort" in result.markdown
assert result.markdown.count("background-color:") >= 4
assert "color: #ffffff" in result.markdown
def test_rejects_legacy_excel():
with pytest.raises(ImportFailure, match="xlsx"):
import_document(Upload(b"", "legacy.xls"))
@@ -68,6 +113,66 @@ def test_excel_multi_sheet_import_creates_one_result_per_sheet():
assert "Leitstelle" in results[1].markdown
def test_excel_import_renders_only_selected_source_sheets():
workbook = Workbook()
first = workbook.active
first.title = "Nicht gewählt"
first.append(["Sehr viele Daten"])
second = workbook.create_sheet("Gewählt")
second.append(["Nur dieses Blatt"])
third = workbook.create_sheet("Auch nicht gewählt")
third.append(["Weitere Daten"])
stream = BytesIO()
workbook.save(stream)
results = import_excel_sheets(
Upload(stream.getvalue(), "auswahl.xlsx"), selected_indexes={1},
)
assert len(results) == 1
assert results[0].title == "Gewählt"
assert results[0].source_index == 1
assert "Nur dieses Blatt" in results[0].markdown
assert "Sehr viele Daten" not in results[0].markdown
def test_excel_metadata_phase_skips_document_rendering():
workbook = Workbook()
sheet = workbook.active
sheet.title = "Großes Blatt"
sheet.append(["Name", "IP"])
sheet.append(["web01", "10.0.0.1"])
stream = BytesIO()
workbook.save(stream)
results = import_excel_sheets(
Upload(stream.getvalue(), "kunde.xlsx"), metadata_only=True,
include_image_data=False,
)
assert [result.title for result in results] == ["Großes Blatt"]
assert results[0].markdown == ""
def test_excel_preview_limits_rows_without_affecting_sheet_detection():
workbook = Workbook()
sheet = workbook.active
sheet.append(["Nummer"])
for number in range(1, 151):
sheet.append([number])
stream = BytesIO()
workbook.save(stream)
results = import_excel_sheets(
Upload(stream.getvalue(), "gross.xlsx"), preview_max_rows=100,
include_image_data=False,
)
assert "Preview limited to 100 rows" in results[0].markdown
assert ">99<" in results[0].markdown
assert ">100<" not in results[0].markdown
def test_excel_flatten_turns_cells_into_document_flow():
workbook = Workbook()
sheet = workbook.active
@@ -78,10 +183,11 @@ def test_excel_flatten_turns_cells_into_document_flow():
results = import_excel_sheets(Upload(stream.getvalue(), "server.xlsx"), flatten=True)
assert results[0].markdown == "Name \nIP\n\ndb01 \n10.0.0.2"
assert results[0].body_format == "html"
assert results[0].markdown == "<p>Name<br>IP</p>\n<p>db01<br>10.0.0.2</p>"
assert "Datensatz" not in results[0].markdown
assert "Feld" not in results[0].markdown
assert "|" not in results[0].markdown
assert "<table" not in results[0].markdown
def test_excel_flatten_preserves_explicit_excel_tables_only():
@@ -100,6 +206,46 @@ def test_excel_flatten_preserves_explicit_excel_tables_only():
markdown = results[0].markdown
assert "Normaler Hinweis" in markdown
assert "| Name" in markdown
assert "| web01" in markdown
assert "<table" in markdown
assert "Name" in markdown
assert "web01" in markdown
assert "Datensatz" not in markdown
def test_excel_flatten_preserves_colors_of_explicit_excel_tables():
workbook = Workbook()
sheet = workbook.active
sheet["A1"] = "Standort"
sheet["B1"] = "Adresse"
sheet["A2"] = "Verwaltung"
sheet["B2"] = "10.1.2.17"
for cell in (sheet["A1"], sheet["B1"]):
cell.fill = PatternFill(fill_type="solid", fgColor="A5BF60")
cell.font = Font(color="FFFFFF", bold=True)
sheet.add_table(Table(displayName="Standorte", ref="A1:B2"))
stream = BytesIO()
workbook.save(stream)
results = import_excel_sheets(Upload(stream.getvalue(), "farben.xlsx"), flatten=True)
assert results[0].body_format == "html"
assert results[0].markdown.count("background-color: #a5bf60") == 2
assert results[0].markdown.count("color: #ffffff") == 2
def test_excel_flatten_preserves_colored_cells_outside_tables():
workbook = Workbook()
sheet = workbook.active
sheet["A1"] = "Wichtiger Hinweis"
sheet["A1"].fill = PatternFill(fill_type="solid", fgColor="FFF3BF")
sheet["A1"].font = Font(color="9C2A2A", bold=True)
sheet["A3"] = "Normaler Text"
stream = BytesIO()
workbook.save(stream)
results = import_excel_sheets(Upload(stream.getvalue(), "hinweis.xlsx"), flatten=True)
assert results[0].body_format == "html"
assert '<span style="background-color: #fff3bf; color: #9c2a2a; font-weight: bold' in results[0].markdown
assert "Wichtiger Hinweis</span>" in results[0].markdown
assert "<table" not in results[0].markdown
+24
View File
@@ -0,0 +1,24 @@
import ast
import re
from pathlib import Path
ROOT = Path(__file__).parents[1]
def plugin_versions():
tree = ast.parse((ROOT / "netbox_documentation" / "__init__.py").read_text())
config = next(node for node in tree.body if isinstance(node, ast.ClassDef))
values = {
target.id: node.value.value
for node in config.body if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
for target in node.targets if isinstance(target, ast.Name)
}
return values["min_version"], values["max_version"]
def test_readme_matches_plugin_version_range():
minimum, maximum = plugin_versions()
expected = f"`{minimum}` – `{'.'.join(maximum.split('.')[:2])}.x`"
readme = (ROOT / "README.md").read_text()
assert re.search(rf"\| \*\*NetBox\*\* \| {re.escape(expected)} \|", readme)
assert f"- NetBox {expected}" in readme