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]>
This commit is contained in:
1 parent
e6995630e9
commit
f557e7d49d
33 files changed
+1564
-314
No files matched your search
@@ -6,7 +6,7 @@ A wiki for operational documentation and how-tos, integrated into NetBox.
|
||||
|---|---|
|
||||
| **Plugin name** | `netbox_documentation` |
|
||||
| **Package** | `netbox-documentation` |
|
||||
| **NetBox** | `>=4.0` |
|
||||
| **NetBox** | `4.4.0` – `4.7.x` |
|
||||
| **Python** | `>=3.10` |
|
||||
| **Repository** | <https://git.mrblake.cc/MrBlake/Netbox-Documentation> |
|
||||
|
||||
@@ -50,7 +50,7 @@ Folder tree:
|
||||
|
||||
## Compatibility
|
||||
|
||||
- NetBox `>=4.0`
|
||||
- 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
|
||||
@@ -267,7 +267,8 @@ pytest
|
||||
```
|
||||
|
||||
Full UI/API tests require NetBox in the same virtualenv. The pure import tests
|
||||
are located in `netbox_documentation/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.
|
||||
|
||||
## Roadmap
|
||||
|
||||
|
||||
@@ -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"
|
||||
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": [
|
||||
|
||||
@@ -8,6 +8,7 @@ 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
|
||||
@@ -113,23 +114,23 @@ 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 _resolve_tenant_group(slug, context):
|
||||
@@ -147,9 +148,10 @@ def _resolve_tenant_group(slug, context):
|
||||
group = TenantGroup.objects.filter(slug=slug).first()
|
||||
if group is None:
|
||||
raise ArchiveFailure(
|
||||
f"{context}: Die Mandantengruppe „{slug}“ existiert auf dieser Instanz nicht. "
|
||||
"Bitte die Mandantengruppe vorher anlegen oder den Import mit einem angepassten "
|
||||
"manifest.json wiederholen."
|
||||
_(
|
||||
"%(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
|
||||
|
||||
@@ -167,9 +169,10 @@ def _resolve_tenant(slug, context):
|
||||
tenant = Tenant.objects.filter(slug=slug).first()
|
||||
if tenant is None:
|
||||
raise ArchiveFailure(
|
||||
f"{context}: Der Mandant „{slug}“ existiert auf dieser Instanz nicht. "
|
||||
"Bitte den Mandanten vorher anlegen oder den Import mit einem angepassten "
|
||||
"manifest.json wiederholen."
|
||||
_(
|
||||
"%(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
|
||||
|
||||
@@ -181,15 +184,15 @@ def _category_from_path(names, tenancy_path=None):
|
||||
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 = f"Ordner „{name}“"
|
||||
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(
|
||||
f"{context}: Der Mandant „{tenant.slug}“ gehört nicht zur "
|
||||
f"Mandantengruppe „{tenant_group.slug}“ auf dieser Instanz."
|
||||
_("%(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:
|
||||
@@ -226,24 +229,24 @@ 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(
|
||||
@@ -260,13 +263,13 @@ 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
|
||||
context = f"Dokument „{document.title}“"
|
||||
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(
|
||||
f"{context}: Der Mandant „{document.tenant.slug}“ gehört nicht zur "
|
||||
f"Mandantengruppe „{document.tenant_group.slug}“ auf dieser Instanz."
|
||||
_("%(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 []:
|
||||
@@ -291,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"):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import re
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
|
||||
class EmbeddedImageError(ValueError):
|
||||
@@ -20,23 +21,23 @@ def _decode(match):
|
||||
try:
|
||||
content = base64.b64decode(payload, validate=True)
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise EmbeddedImageError("Ein eingefügtes Bild enthält ungültige Base64-Daten.") from 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("Ein eingefügter Inhalt ist keine gültige Bilddatei.") from 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 ""):
|
||||
_, content = _decode(match)
|
||||
_mime, content = _decode(match)
|
||||
total += len(content)
|
||||
if total > max_total_bytes:
|
||||
raise EmbeddedImageError("Die eingefügten Bilder überschreiten die erlaubte Gesamtgröße.")
|
||||
raise EmbeddedImageError(_("The pasted images exceed the allowed total size."))
|
||||
|
||||
|
||||
def store_embedded_images(html, max_total_bytes, store):
|
||||
@@ -47,7 +48,7 @@ def store_embedded_images(html, max_total_bytes, store):
|
||||
mime, content = _decode(match)
|
||||
total += len(content)
|
||||
if total > max_total_bytes:
|
||||
raise EmbeddedImageError("Die eingefügten Bilder überschreiten die erlaubte Gesamtgröße.")
|
||||
raise EmbeddedImageError(_("The pasted images exceed the allowed total size."))
|
||||
url = store(mime, content)
|
||||
return f'{match.group("prefix")}{url}{match.group("quote")}'
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@ 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,
|
||||
@@ -17,7 +20,7 @@ from .embedded_images import EmbeddedImageError, store_embedded_images, validate
|
||||
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>',
|
||||
@@ -25,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", []
|
||||
@@ -38,22 +44,22 @@ 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="Mandantengruppe",
|
||||
queryset=TenantGroup.objects.all(), required=False, selector=True, label=_("Tenant group"),
|
||||
)
|
||||
tenant = DynamicModelChoiceField(
|
||||
queryset=Tenant.objects.all(), required=False, selector=True, label="Mandant",
|
||||
queryset=Tenant.objects.all(), required=False, selector=True, label=_("Tenant"),
|
||||
query_params={"group_id": "$tenant_group"},
|
||||
)
|
||||
|
||||
fieldsets = (
|
||||
FieldSet("title", "slug", "category", "tenant_group", "tenant", "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:
|
||||
@@ -83,7 +89,7 @@ class DocumentForm(NetBoxModelForm):
|
||||
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", "Der Mandant gehört nicht zur ausgewählten Mandantengruppe.")
|
||||
self.add_error("tenant", _("The tenant does not belong to the selected tenant group."))
|
||||
return cleaned
|
||||
|
||||
def save(self, commit=True):
|
||||
@@ -98,7 +104,7 @@ class DocumentForm(NetBoxModelForm):
|
||||
nonlocal counter
|
||||
counter += 1
|
||||
extension = {"image/jpeg": "jpg", "image/png": "png", "image/gif": "gif", "image/webp": "webp"}[mime]
|
||||
name = f"editor-bild-{document.pk}-{counter}.{extension}"
|
||||
name = f"editor-image-{document.pk}-{counter}.{extension}"
|
||||
attachment = DocumentAttachment(
|
||||
document=document, original_name=name, content_type=mime, size=len(content),
|
||||
)
|
||||
@@ -112,12 +118,12 @@ class DocumentForm(NetBoxModelForm):
|
||||
|
||||
|
||||
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
|
||||
@@ -149,16 +155,16 @@ 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="Mandantengruppe",
|
||||
queryset=TenantGroup.objects.all(), required=False, selector=True, label=_("Tenant group"),
|
||||
)
|
||||
tenant = DynamicModelChoiceField(
|
||||
queryset=Tenant.objects.all(), required=False, selector=True, label="Mandant",
|
||||
queryset=Tenant.objects.all(), required=False, selector=True, label=_("Tenant"),
|
||||
query_params={"group_id": "$tenant_group"},
|
||||
)
|
||||
|
||||
fieldsets = (FieldSet("name", "slug", "parent", "tenant_group", "tenant", "description", "tags", name="Ordner"),)
|
||||
fieldsets = (FieldSet("name", "slug", "parent", "tenant_group", "tenant", "description", "tags", name=_("Folder")),)
|
||||
|
||||
class Meta:
|
||||
model = DocumentCategory
|
||||
@@ -174,38 +180,38 @@ class DocumentCategoryForm(NetBoxModelForm):
|
||||
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", "Der Mandant gehört nicht zur ausgewählten Mandantengruppe.")
|
||||
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):
|
||||
@@ -217,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):
|
||||
@@ -252,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
|
||||
|
||||
|
||||
@@ -294,13 +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("Ausgewählte Arbeitsblätter dürfen nicht denselben Dokumenttitel haben.")
|
||||
raise forms.ValidationError(_("Selected worksheets must not have the same document title."))
|
||||
|
||||
|
||||
ExcelSheetSelectionFormSet = forms.formset_factory(
|
||||
|
||||
@@ -4,6 +4,8 @@ from pathlib import Path
|
||||
from html import escape
|
||||
import re
|
||||
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
|
||||
class ImportFailure(ValueError):
|
||||
pass
|
||||
@@ -46,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):
|
||||
@@ -95,7 +97,7 @@ def _xlsx(content, flatten=False):
|
||||
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.")
|
||||
raise ImportFailure(_("The workbook contains no data."))
|
||||
return ImportResult("\n\n".join(sections), body_format="html")
|
||||
|
||||
|
||||
@@ -109,7 +111,7 @@ def import_excel_sheets(
|
||||
|
||||
suffix = Path(upload.name).suffix.lower()
|
||||
if suffix not in {".xlsx", ".xlsm"}:
|
||||
raise ImportFailure("Der Mehrblattimport unterstützt XLSX- und XLSM-Dateien.")
|
||||
raise ImportFailure(_("The multi-sheet import supports XLSX and XLSM files."))
|
||||
upload.seek(0)
|
||||
workbook = load_workbook(upload, read_only=False, data_only=True)
|
||||
results = []
|
||||
@@ -156,7 +158,7 @@ def import_excel_sheets(
|
||||
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
|
||||
|
||||
|
||||
@@ -348,7 +350,7 @@ def _render_excel_worksheet_html(sheet, workbook, max_rows=None, bounds=None):
|
||||
output.append("</tr>")
|
||||
output.append("</tbody></table>")
|
||||
if max_rows and last_row > start_row + max_rows - 1:
|
||||
output.append(f"<p><em>Vorschau auf {max_rows} Zeilen begrenzt.</em></p>")
|
||||
output.append("<p><em>%s</em></p>" % escape(_("Preview limited to %(rows)s rows.") % {"rows": max_rows}))
|
||||
return "".join(output)
|
||||
|
||||
|
||||
@@ -398,7 +400,7 @@ def _render_flattened_worksheet(sheet, workbook, max_rows=None):
|
||||
bounds=(min_col, min_row, max_col, min(max_row, rendered_max_row)),
|
||||
))
|
||||
if max_rows and sheet.max_row > max_rows:
|
||||
blocks.append(f"<p><em>Vorschau auf {max_rows} von {sheet.max_row} Zeilen begrenzt.</em></p>")
|
||||
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>"
|
||||
|
||||
|
||||
@@ -410,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
@@ -3,33 +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",
|
||||
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",
|
||||
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):
|
||||
@@ -75,23 +78,24 @@ class Document(NetBoxModel):
|
||||
|
||||
|
||||
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",
|
||||
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",
|
||||
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]
|
||||
@@ -125,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",
|
||||
@@ -158,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
|
||||
|
||||
@@ -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_tree", 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_tree", 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",
|
||||
)
|
||||
@@ -1,11 +1,12 @@
|
||||
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):
|
||||
@@ -14,8 +15,8 @@ class DocumentTable(NetBoxTable):
|
||||
|
||||
|
||||
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):
|
||||
@@ -25,7 +26,7 @@ class DocumentCategoryTable(NetBoxTable):
|
||||
|
||||
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 }}
|
||||
@@ -109,30 +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.tenant_group or object.tenant %}<div class="card mb-3"><h5 class="card-header">Mandantenzuordnung</h5><div class="list-group list-group-flush">
|
||||
{% 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">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.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>
|
||||
@@ -159,7 +160,7 @@
|
||||
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;
|
||||
@@ -174,7 +175,7 @@
|
||||
const copyButton = document.createElement('button');
|
||||
copyButton.type = 'button';
|
||||
copyButton.className = 'doc-code-copy';
|
||||
copyButton.innerHTML = '<i class="mdi mdi-content-copy"></i> Kopieren';
|
||||
copyButton.innerHTML = '<i class="mdi mdi-content-copy"></i> {{ _("Copy")|escapejs }}';
|
||||
copyButton.addEventListener('click', async () => {
|
||||
const text = pre.innerText.trimEnd();
|
||||
try {
|
||||
@@ -190,8 +191,8 @@
|
||||
document.execCommand('copy');
|
||||
area.remove();
|
||||
}
|
||||
copyButton.innerHTML = '<i class="mdi mdi-check"></i> Kopiert';
|
||||
setTimeout(() => { copyButton.innerHTML = '<i class="mdi mdi-content-copy"></i> Kopieren'; }, 1500);
|
||||
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) {
|
||||
|
||||
@@ -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,6 +30,9 @@
|
||||
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 codesample fullscreen image link lists media preview searchreplace table visualblocks wordcount',
|
||||
@@ -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',
|
||||
@@ -95,14 +99,14 @@
|
||||
codesample_languages: [
|
||||
{text: 'Bash / Shell', value: 'bash'},
|
||||
{text: 'PowerShell', value: 'powershell'},
|
||||
{text: 'Cisco / Netzwerk-Konfiguration', value: 'none'},
|
||||
{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: 'Nur Text', value: 'plaintext'}
|
||||
{text: '{{ _("Plain text")|escapejs }}', value: 'plaintext'}
|
||||
],
|
||||
browser_spellcheck: true,
|
||||
contextmenu: 'link image table codesample',
|
||||
@@ -127,7 +131,7 @@
|
||||
if (!file) return;
|
||||
const allowedTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
window.alert('Unterstützt werden PNG, JPEG, GIF und WebP.');
|
||||
window.alert('{{ _("Supported formats are PNG, JPEG, GIF and WebP.")|escapejs }}');
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
@@ -135,7 +139,7 @@
|
||||
alt: file.name,
|
||||
title: file.name
|
||||
}));
|
||||
reader.addEventListener('error', () => window.alert('Das Bild konnte nicht gelesen werden.'));
|
||||
reader.addEventListener('error', () => window.alert('{{ _("The image could not be read.")|escapejs }}'));
|
||||
reader.readAsDataURL(file);
|
||||
}, {once: true});
|
||||
picker.click();
|
||||
@@ -170,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',
|
||||
@@ -184,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('')}
|
||||
])
|
||||
});
|
||||
}
|
||||
@@ -202,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));
|
||||
})
|
||||
@@ -214,6 +218,6 @@
|
||||
|
||||
{% block pre_form_fields %}
|
||||
{% if not object.pk %}
|
||||
<div class="alert alert-info">Eingefügte oder hineinkopierte Bilder werden beim ersten Speichern automatisch als Medien der neuen Dokumentation abgelegt. Nach dem ersten Speichern ist zusätzlich der direkte Bildupload verfügbar.</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; }
|
||||
@@ -56,19 +57,19 @@
|
||||
</head>
|
||||
<body>
|
||||
<div class="toolbar">
|
||||
<button type="button" onclick="window.print()">Drucken / Als PDF speichern</button>
|
||||
<a href="?orientation=portrait"{% if request.GET.orientation != 'landscape' %} class="active"{% endif %}>Hochformat</a>
|
||||
<a href="?orientation=landscape"{% if request.GET.orientation == 'landscape' %} class="active"{% endif %}>Querformat</a>
|
||||
<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{% 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>
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
{% extends 'base/layout.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}Dokumentationen{% endblock %}
|
||||
{% 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="Dokumente & Ordner durchsuchen…">
|
||||
<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> Hinzufügen</a>
|
||||
<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> Neuer Ordner</a>
|
||||
<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="Ansicht">
|
||||
<button type="button" class="btn btn-outline-secondary" data-view="explorer" title="Explorer-Ansicht"><i class="mdi mdi-view-grid-outline"></i> Explorer</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-view="tree" title="Baumansicht"><i class="mdi mdi-file-tree"></i> Baum</button>
|
||||
<a href="{% url 'plugins:netbox_documentation:document_list' %}" class="btn btn-outline-secondary" title="Listenansicht"><i class="mdi mdi-format-list-bulleted"></i> Liste</a>
|
||||
<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>
|
||||
@@ -25,14 +26,14 @@
|
||||
{% 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="Zurück"><i class="mdi mdi-arrow-left"></i></button>
|
||||
<button type="button" class="btn btn-sm btn-ghost-secondary" id="doc-explorer-up" title="Übergeordneter Ordner (Rücktaste)"><i class="mdi mdi-arrow-up"></i></button>
|
||||
<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="Ordnerdetails"><i class="mdi mdi-information-outline"></i></a>
|
||||
<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>Dokumentationen</span></div>
|
||||
<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 %}
|
||||
@@ -40,7 +41,7 @@
|
||||
</ul>
|
||||
</aside>
|
||||
<section class="netbox-explorer-content">
|
||||
<div class="netbox-explorer-pane" data-folder="root" data-parent="" data-title="Dokumentationen">
|
||||
<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 %}
|
||||
@@ -52,7 +53,7 @@
|
||||
{% 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">Keine Treffer gefunden.</p>
|
||||
<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>
|
||||
@@ -79,7 +80,7 @@
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="text-muted mb-0">Noch keine Dokumentationen vorhanden.</p>
|
||||
<p class="text-muted mb-0">{% trans "No documents yet." %}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
@@ -129,6 +130,29 @@
|
||||
|
||||
<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');
|
||||
@@ -193,7 +217,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
applySearch();
|
||||
}
|
||||
|
||||
// Point "Hinzufügen" / "Neuer Ordner" at the open folder and return here afterwards.
|
||||
// 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 : '');
|
||||
@@ -223,7 +247,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
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 || '') + folders + ' Ordner, ' + files + ' Dokument(e)';
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -254,7 +278,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
});
|
||||
});
|
||||
results.classList.remove('d-none');
|
||||
updateStatus(results, 'Suchergebnisse in allen Ordnern: ');
|
||||
updateStatus(results, T.searchResults);
|
||||
}
|
||||
|
||||
if (explorer) {
|
||||
@@ -314,41 +338,41 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
if (!tile) {
|
||||
var here = pane(current);
|
||||
return [
|
||||
addFolder && { icon: 'mdi-folder-plus-outline', label: 'Neuer Ordner', run: function () { go(addFolder.href); } },
|
||||
addDoc && { icon: 'mdi-file-document-plus-outline', label: 'Neues Dokument', run: function () { go(addDoc.href); } },
|
||||
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: 'Ordner als ZIP exportieren', run: function () { exportFolder(current); } },
|
||||
here.dataset.url && { icon: 'mdi-information-outline', label: 'Ordnerdetails', run: function () { go(here.dataset.url); } },
|
||||
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: 'Aktualisieren', run: function () { window.location.reload(); } }
|
||||
{ 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: 'Öffnen', bold: true, run: function () { if (input) input.value = ''; openFolder(d.pk); } },
|
||||
{ icon: 'mdi-information-outline', label: 'Ordnerdetails', run: function () { go(d.url); } },
|
||||
{ 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: 'Neuer Unterordner', run: function () { go(withReturn(addFolder.dataset.base, { parent: d.pk })); } },
|
||||
addDoc && { icon: 'mdi-file-document-plus-outline', label: 'Neues Dokument hier', run: function () { go(withReturn(addDoc.dataset.base, { category: d.pk })); } },
|
||||
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: 'Umbenennen / Bearbeiten', run: function () { go(withReturn(d.edit)); } },
|
||||
{ icon: 'mdi-folder-zip-outline', label: 'Als ZIP exportieren', run: function () { exportFolder(d.pk); } },
|
||||
{ icon: 'mdi-link-variant', label: 'Link kopieren', run: function () { copyText(window.location.origin + window.location.pathname + '?folder=' + 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: 'Löschen', danger: true, run: function () { go(withReturn(d.delete)); } }
|
||||
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: 'Öffnen', bold: true, run: function () { go(href); } },
|
||||
{ icon: 'mdi-open-in-new', label: 'In neuem Tab öffnen', run: function () { go(href, true); } },
|
||||
{ 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: 'Umbenennen / Bearbeiten', run: function () { go(withReturn(d.edit)); } },
|
||||
{ icon: 'mdi-printer-outline', label: 'Drucken / als PDF exportieren', run: function () { go(d.print, true); } },
|
||||
{ icon: 'mdi-link-variant', label: 'Link kopieren', run: function () { copyText(new URL(href, window.location.href).href); } },
|
||||
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: 'Löschen', danger: true, run: function () { go(withReturn(d.delete)); } }
|
||||
d.delete && { icon: 'mdi-trash-can-outline', label: T.delete, danger: true, run: function () { go(withReturn(d.delete)); } }
|
||||
];
|
||||
}
|
||||
|
||||
@@ -422,7 +446,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
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="Schließen"></button></div>';
|
||||
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);
|
||||
@@ -446,7 +470,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
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">Dieser Ordner ist leer.</p>');
|
||||
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)';
|
||||
@@ -468,17 +492,17 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
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: 'Unerwartete Antwort vom Server (' + r.status + ').' }; }); })
|
||||
.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('„' + doc.title + '“ verschoben nach „' + pane(folderId).dataset.title + '“.', true);
|
||||
toast(T.moved.replace('{document}', doc.title).replace('{folder}', pane(folderId).dataset.title), true);
|
||||
applySearch();
|
||||
})
|
||||
.catch(function () { toast('Verschieben fehlgeschlagen – keine Verbindung zum Server.', false); });
|
||||
.catch(function () { toast(T.moveFailed, false); });
|
||||
}
|
||||
|
||||
if (explorer) {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<nav aria-label="breadcrumb" class="mb-3">
|
||||
<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> Ordner</a></li>
|
||||
<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 %}
|
||||
@@ -14,7 +15,7 @@
|
||||
<div class="col col-md-4">
|
||||
{% if object.tenant_group or object.tenant %}
|
||||
<div class="card mb-3">
|
||||
<h5 class="card-header">Mandantenzuordnung</h5>
|
||||
<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 %}
|
||||
@@ -22,21 +23,21 @@
|
||||
</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>
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
{% extends 'base/layout.html' %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block title %}Ordner & Kategorien{% endblock %}
|
||||
{% 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="Ordner durchsuchen…">
|
||||
<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> Ordner erstellen</a>
|
||||
<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> Listenansicht</a>
|
||||
<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>
|
||||
@@ -23,7 +24,7 @@
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="text-muted mb-0">Noch keine Ordner vorhanden.</p>
|
||||
<p class="text-muted mb-0">{% trans "No folders yet." %}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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 }}
|
||||
@@ -17,9 +18,9 @@
|
||||
<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>
|
||||
@@ -29,8 +30,8 @@
|
||||
{% if overwrite_conflicts %}
|
||||
<input type="hidden" name="confirm_overwrite" value="1">
|
||||
<div class="alert alert-warning mx-0" role="alert">
|
||||
<h3 class="alert-title">Bestehende Dokumentationen aktualisieren?</h3>
|
||||
<p>Die folgenden Dokumentationen existieren bereits im Zielordner. Ihr Inhalt wird überschrieben; bestehende NetBox-Zuordnungen bleiben erhalten:</p>
|
||||
<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>
|
||||
@@ -45,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>
|
||||
@@ -71,10 +72,10 @@
|
||||
|
||||
<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="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 %}Überschreiben und importieren{% else %}Ausgewählte Arbeitsblätter importieren{% endif %}
|
||||
{% if overwrite_conflicts %}{% trans "Overwrite and import" %}{% else %}{% trans "Import selected worksheets" %}{% endif %}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
{% load i18n %}
|
||||
<li class="netbox-doc-tree-item" data-name="{{ node.object.name|lower }}">
|
||||
{% if node.children %}
|
||||
<details open>
|
||||
@@ -7,7 +8,7 @@
|
||||
<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="Bearbeiten"><i class="mdi mdi-pencil"></i></a>
|
||||
<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">
|
||||
@@ -23,7 +24,7 @@
|
||||
<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="Bearbeiten"><i class="mdi mdi-pencil"></i></a>
|
||||
<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 %}
|
||||
|
||||
@@ -1,8 +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">Entwurf</span>{% endif %}
|
||||
{% 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>
|
||||
@@ -1,3 +1,4 @@
|
||||
{% load i18n %}
|
||||
<li class="netbox-doc-tree-item" data-name="{{ node.object.name|lower }}">
|
||||
<details open>
|
||||
<summary class="netbox-doc-tree-summary">
|
||||
@@ -13,7 +14,7 @@
|
||||
{% 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">Leer</li>
|
||||
<li class="netbox-doc-tree-empty text-muted">{% trans "Empty" %}</li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
@@ -1,9 +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">Entwurf</span>{% endif %}
|
||||
{% 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>
|
||||
@@ -1,8 +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 %}{{ c|add:d }}{% endwith %} Element(e)</small>
|
||||
<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>
|
||||
@@ -1,3 +1,4 @@
|
||||
{% 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 %}
|
||||
@@ -5,7 +6,7 @@
|
||||
{% 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">Dieser Ordner ist leer.</p>{% endif %}
|
||||
{% 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 %}
|
||||
|
||||
@@ -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>
|
||||
@@ -12,6 +12,7 @@ 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
|
||||
@@ -138,7 +139,7 @@ class DocumentMoveView(PermissionRequiredMixin, View):
|
||||
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": "Der Zielordner existiert nicht."}, status=404)
|
||||
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
|
||||
@@ -255,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")
|
||||
@@ -269,7 +270,7 @@ 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():
|
||||
@@ -289,7 +290,7 @@ 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):
|
||||
@@ -299,7 +300,7 @@ class DocumentImportView(PermissionRequiredMixin, View):
|
||||
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))
|
||||
@@ -343,14 +344,19 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
for form, sheet in zip(formset.forms, sheets):
|
||||
sample = sheet.markdown
|
||||
if sheet.images:
|
||||
image_notice = f"{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>Bilder</h2><p><em>{image_notice}</em></p>"
|
||||
sample += f"\n<h2>{escape(images_heading)}</h2><p><em>{escape(image_notice)}</em></p>"
|
||||
else:
|
||||
sample += f"\n\n## Bilder\n\n_{image_notice}_"
|
||||
sample += f"\n\n## {images_heading}\n\n_{image_notice}_"
|
||||
truncated = len(sample) > 100000
|
||||
if truncated:
|
||||
notice = "… Vorschau gekürzt …"
|
||||
notice = _("… preview truncated …")
|
||||
sample = sample[:100000] + (
|
||||
f"<p><em>{notice}</em></p>" if sheet.body_format == "html" else f"\n\n_{notice}_"
|
||||
)
|
||||
@@ -368,13 +374,13 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
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, 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))
|
||||
@@ -383,7 +389,7 @@ 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.")
|
||||
messages.info(request, _("Excel import was cancelled."))
|
||||
return redirect("plugins:netbox_documentation:document_import")
|
||||
formset = ExcelSheetSelectionFormSet(request.POST)
|
||||
if not formset.is_valid():
|
||||
@@ -391,12 +397,12 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
preview_sheets = self.read_sheets(preview, for_preview=True)
|
||||
except (ImportFailure, Exception) as exc:
|
||||
self.delete_preview(preview)
|
||||
messages.error(request, f"Die Exceldatei konnte nicht erneut gelesen werden: {exc}")
|
||||
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:
|
||||
@@ -418,13 +424,13 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
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, "Mindestens eine gleichnamige Dokumentation darf nicht aktualisiert werden.")
|
||||
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, f"Die Bestätigung konnte nicht angezeigt werden: {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,
|
||||
@@ -433,16 +439,15 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
try:
|
||||
selected_sheets = self.read_sheets(preview, selected_indexes=selections)
|
||||
except (ImportFailure, Exception) as exc:
|
||||
messages.error(request, f"Die ausgewählten Excel-Blätter konnten nicht importiert werden: {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 verarbeitet "
|
||||
f"({result['created']} neu, {result['updated']} aktualisiert) in „{result['category']}“; "
|
||||
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
|
||||
@@ -459,7 +464,7 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
document.title = title[:200]
|
||||
document.body = sheet.markdown
|
||||
document.body_format = sheet.body_format
|
||||
document.summary = f"Importiert aus {preview.original_name}"
|
||||
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=(
|
||||
@@ -467,7 +472,7 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
))
|
||||
updated_count += 1
|
||||
else:
|
||||
base_slug = slugify(title)[:180] or "arbeitsblatt"
|
||||
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}"
|
||||
@@ -476,7 +481,7 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
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=f"Importiert aus {preview.original_name}",
|
||||
summary=_("Imported from %(name)s") % {"name": preview.original_name},
|
||||
)
|
||||
created_count += 1
|
||||
if sheet.images:
|
||||
@@ -496,9 +501,9 @@ class ExcelImportPreviewView(PermissionRequiredMixin, View):
|
||||
else:
|
||||
image_lines.append(f"")
|
||||
if document.body_format == "html":
|
||||
document.body += "\n<h2>Bilder</h2>\n" + "\n".join(image_lines)
|
||||
document.body += f"\n<h2>{escape(_('Images'))}</h2>\n" + "\n".join(image_lines)
|
||||
else:
|
||||
document.body += "\n\n## Bilder\n\n" + "\n\n".join(image_lines)
|
||||
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)
|
||||
@@ -532,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,
|
||||
@@ -579,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")
|
||||
@@ -604,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)
|
||||
+6
-1
@@ -28,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"]
|
||||
@@ -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()
|
||||
@@ -43,6 +43,6 @@ def test_embedded_images_respect_total_size_limit():
|
||||
try:
|
||||
embedded.validate_embedded_images(html, 1)
|
||||
except embedded.EmbeddedImageError as exc:
|
||||
assert "Gesamtgröße" in str(exc)
|
||||
assert "total size" in str(exc)
|
||||
else:
|
||||
raise AssertionError("Größenlimit wurde nicht angewendet")
|
||||
raise AssertionError("size limit was not applied")
|
||||
@@ -168,7 +168,7 @@ def test_excel_preview_limits_rows_without_affecting_sheet_detection():
|
||||
include_image_data=False,
|
||||
)
|
||||
|
||||
assert "Vorschau auf 100 Zeilen begrenzt" in results[0].markdown
|
||||
assert "Preview limited to 100 rows" in results[0].markdown
|
||||
assert ">99<" in results[0].markdown
|
||||
assert ">100<" not in results[0].markdown
|
||||
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user