diff --git a/netbox_utilities/disk_forms.py b/netbox_utilities/disk_forms.py index 18d16e1..c81e6b9 100644 --- a/netbox_utilities/disk_forms.py +++ b/netbox_utilities/disk_forms.py @@ -144,7 +144,8 @@ class DiskBayLayoutForm(forms.ModelForm): } def clean(self): - cleaned_data = super().clean() + super().clean() + cleaned_data = self.cleaned_data slot_count, rows = cleaned_data.get("slot_count"), cleaned_data.get("rows") if slot_count and rows and rows > slot_count: self.add_error("rows", "Es kann nicht mehr Reihen als Steckplätze geben.") @@ -190,7 +191,8 @@ class DiskBulkFillForm(forms.Form): widget.attrs["class"] = f"{css} {widget.attrs.get('class', '')}".strip() def clean(self): - cleaned_data = super().clean() + super().clean() + cleaned_data = self.cleaned_data slots = cleaned_data.get("slots") or [] serials = disks.parse_serials(cleaned_data.get("serials")) if len(serials) > len(slots): @@ -275,7 +277,8 @@ class RAIDGroupForm(NetBoxModelForm): self.initial["members"] = list(self.instance.disks.values_list("pk", flat=True)) def clean(self): - cleaned_data = super().clean() + super().clean() + cleaned_data = self.cleaned_data device = cleaned_data.get("device") foreign = [disk for disk in cleaned_data.get("members") or () if device and disk.device_id != device.pk] if foreign: @@ -391,7 +394,8 @@ class DiskImportForm(NetBoxModelImportForm): return self.cleaned_data.get("raid_group") or "" def clean(self): - cleaned_data = super().clean() + super().clean() + cleaned_data = self.cleaned_data if cleaned_data.get("status") in (None, ""): cleaned_data["status"] = disks.STATUS_ACTIVE self.instance.status = disks.STATUS_ACTIVE diff --git a/netbox_utilities/disk_views.py b/netbox_utilities/disk_views.py index d090ffb..5d24c1b 100644 --- a/netbox_utilities/disk_views.py +++ b/netbox_utilities/disk_views.py @@ -4,6 +4,7 @@ from dcim.models import Device from django.contrib import messages from django.core.exceptions import ValidationError from django.db import transaction +from django.http import JsonResponse from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from django.views import View @@ -198,6 +199,62 @@ class DeviceDiskBulkFillView(_DeviceDiskActionView): ) +# Parking slot while two disks swap places; the unique (device, slot) constraint +# would otherwise reject the intermediate state. +SWAP_PARKING_SLOT = 32767 + + +class DeviceDiskMoveView(ContentTypePermissionRequiredMixin, View): + """Drag and drop on the slot grid: move a disk to a free slot or swap two disks.""" + + http_method_names = ["post"] + + def get_required_permission(self): + return "netbox_utilities.change_disk" + + def post(self, request, pk): + device = get_object_or_404(Device.objects.restrict(request.user, "view"), pk=pk) + layout = get_object_or_404(DiskBayLayout, device=device) + installed = Disk.objects.restrict(request.user, "change").filter( + device=device, status__in=disks.SLOT_OCCUPYING_STATUSES + ) + try: + disk = installed.get(pk=int(request.POST.get("disk", ""))) + target_slot = int(request.POST.get("slot", "")) + except (ValueError, Disk.DoesNotExist): + return JsonResponse({"error": "Unbekannter Datenträger oder Steckplatz."}, status=400) + if not layout.first_slot <= target_slot <= layout.last_slot: + return JsonResponse({"error": f"Steckplatz {target_slot} existiert nicht."}, status=400) + if target_slot == disk.slot: + return JsonResponse({"moved": []}) + + source_slot = disk.slot + with transaction.atomic(): + other = ( + Disk.objects.select_for_update() + .filter(device=device, slot=target_slot, status__in=disks.SLOT_OCCUPYING_STATUSES) + .first() + ) + if other is not None and not installed.filter(pk=other.pk).exists(): + return JsonResponse({"error": "Keine Berechtigung für den Datenträger im Ziel."}, status=403) + + disk.snapshot() + if other is not None: + other.snapshot() + disk.slot = SWAP_PARKING_SLOT + disk.save() + other.slot = source_slot + other.save() + disk.slot = target_slot + disk.save() + + if other is None: + messages.success(request, f"{disk} wurde von Slot {source_slot} nach Slot {target_slot} verschoben.") + else: + messages.success(request, f"Slot {source_slot} und Slot {target_slot} wurden getauscht.") + return JsonResponse({"moved": [disk.pk] + ([other.pk] if other else [])}) + + class DiskReplaceView(ContentTypePermissionRequiredMixin, View): """Mark a disk as removed and open a pre-filled form for its successor in the same slot.""" diff --git a/netbox_utilities/static/netbox_utilities/disks.js b/netbox_utilities/static/netbox_utilities/disks.js index 53f46c9..2748c3e 100644 --- a/netbox_utilities/static/netbox_utilities/disks.js +++ b/netbox_utilities/static/netbox_utilities/disks.js @@ -30,6 +30,70 @@ update(); } + function initDragAndDrop(grid) { + const moveUrl = grid.dataset.nbuMoveUrl; + if (!moveUrl) return; + let dragged = null; + + const targetOf = (event) => { + const slot = event.target.closest("[data-nbu-slot]"); + return slot && grid.contains(slot) && slot !== dragged ? slot : null; + }; + const clearTargets = () => { + for (const slot of grid.querySelectorAll(".nbu-disk-drop-target")) { + slot.classList.remove("nbu-disk-drop-target"); + } + }; + + grid.addEventListener("dragstart", (event) => { + dragged = event.target.closest("[data-nbu-disk]"); + if (!dragged) return; + event.dataTransfer.effectAllowed = "move"; + event.dataTransfer.setData("text/plain", dragged.dataset.nbuDisk); + dragged.classList.add("nbu-disk-dragging"); + }); + grid.addEventListener("dragend", () => { + if (dragged) dragged.classList.remove("nbu-disk-dragging"); + dragged = null; + clearTargets(); + }); + grid.addEventListener("dragover", (event) => { + const target = dragged && targetOf(event); + if (!target) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + clearTargets(); + target.classList.add("nbu-disk-drop-target"); + }); + grid.addEventListener("dragleave", (event) => { + if (!grid.contains(event.relatedTarget)) clearTargets(); + }); + grid.addEventListener("drop", async (event) => { + const target = dragged && targetOf(event); + if (!target) return; + event.preventDefault(); + const body = new FormData(); + body.append("disk", dragged.dataset.nbuDisk); + body.append("slot", target.dataset.nbuSlot); + grid.classList.add("nbu-disk-busy"); + try { + const response = await fetch(moveUrl, { + method: "POST", + body, + headers: { "X-CSRFToken": grid.dataset.nbuCsrf }, + credentials: "same-origin", + }); + const result = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(result.error || `HTTP ${response.status}`); + window.location.reload(); + } catch (error) { + grid.classList.remove("nbu-disk-busy"); + clearTargets(); + window.alert(`Verschieben fehlgeschlagen: ${error.message}`); + } + }); + } + function initFillForm(form) { const textarea = form.querySelector("textarea[name='serials']"); const status = form.querySelector("[data-nbu-serial-status]"); @@ -66,7 +130,11 @@ document.addEventListener("DOMContentLoaded", () => { const grid = document.getElementById("nbu-disk-grid-form"); - if (grid) initSlotGrid(grid); + if (grid) { + initSlotGrid(grid); + const slots = grid.querySelector(".nbu-disk-grid"); + if (slots) initDragAndDrop(slots); + } const fill = document.getElementById("nbu-disk-fill-form"); if (fill) initFillForm(fill); }); diff --git a/netbox_utilities/static/netbox_utilities/netbox_utilities.css b/netbox_utilities/static/netbox_utilities/netbox_utilities.css index 766ef40..744f77b 100644 --- a/netbox_utilities/static/netbox_utilities/netbox_utilities.css +++ b/netbox_utilities/static/netbox_utilities/netbox_utilities.css @@ -362,3 +362,22 @@ a.nbu-disk-slot:hover, .nbu-disk-fill-slot input { margin-right: 0.25rem; } + +a.nbu-disk-slot[draggable="true"] { + cursor: grab; +} + +.nbu-disk-dragging { + opacity: 0.4; +} + +.nbu-disk-drop-target { + outline: 2px dashed var(--tblr-primary); + outline-offset: 2px; + background: rgba(var(--tblr-primary-rgb), 0.08); +} + +.nbu-disk-busy { + pointer-events: none; + opacity: 0.6; +} diff --git a/netbox_utilities/templates/netbox_utilities/device_disks.html b/netbox_utilities/templates/netbox_utilities/device_disks.html index f22a8d0..2820a6e 100644 --- a/netbox_utilities/templates/netbox_utilities/device_disks.html +++ b/netbox_utilities/templates/netbox_utilities/device_disks.html @@ -112,13 +112,15 @@
-
+
{% for row in grid %}{% for cell in row %} {% if cell.number is None %} {% elif cell.disk %} {% with disk=cell.disk %} {{ cell.number }} {% if disk.warnings %}{% endif %} @@ -129,7 +131,7 @@ {% endwith %} {% else %} -
+
{{ cell.number }} {% if perms.netbox_utilities.add_disk %} @@ -150,7 +152,7 @@ Defekt Geplant Frei - Klick auf einen Steckplatz öffnet bzw. bestückt ihn, Häkchen wählen mehrere freie Steckplätze aus. + Klick auf einen Steckplatz öffnet bzw. bestückt ihn, Häkchen wählen mehrere freie Steckplätze aus.{% if perms.netbox_utilities.change_disk %} Datenträger per Drag & Drop verschieben; auf einen belegten Steckplatz gezogen, tauschen beide die Plätze.{% endif %}
{% if orphaned_disks %}
diff --git a/netbox_utilities/urls.py b/netbox_utilities/urls.py index 187c96c..5df5e35 100644 --- a/netbox_utilities/urls.py +++ b/netbox_utilities/urls.py @@ -27,4 +27,5 @@ urlpatterns = [ path("disk-templates//", include(get_model_urls("netbox_utilities", "diskbaytemplate"))), path("devices//disks/setup/", disk_views.DeviceDiskSetupView.as_view(), name="device_disk_setup"), path("devices//disks/fill/", disk_views.DeviceDiskBulkFillView.as_view(), name="device_disk_fill"), + path("devices//disks/move/", disk_views.DeviceDiskMoveView.as_view(), name="device_disk_move"), ]