diff --git a/docs/panel-design.md b/docs/panel-design.md index a097359..006ac93 100644 --- a/docs/panel-design.md +++ b/docs/panel-design.md @@ -93,7 +93,9 @@ heading, help, fields, and actions should share a left edge. workflow. Keep the final destructive confirmation visually distinct. - Keep a record name and its secondary identifier in one table cell. Use a wrapping row when space permits, and omit the identifier when it repeats - the name. The record name remains the link. + the name. The record name remains the link. The local and cluster + hosting inventories use a separate, right-aligned **Primary domain** + column immediately before **Status** for easy comparison. - Group table actions in a wrapping `.table-actions` container. Center them vertically within the row and allow labels to wrap instead of widening the whole table. Keep overflow within `.table-scroll`. @@ -135,6 +137,21 @@ Django's label association, error state, and description IDs. ``` +### Action feedback + +Use Django messages for the immediate outcome of signed-in actions. +The shared shell displays them as dismissible notifications with JavaScript +and in the page flow without it. Distinguish **queued** from **complete**. +Keep validation next to the relevant field and show a clear summary near +the start of long forms. Don't make notifications the only place to find +errors, progress, or recovery instructions. + +Live regions may opt in to a notification on a meaningful state transition +using `data-live-state`, `data-live-notice` and an optional +`data-live-notice-level`. Notify only once for a transition, not for each +poll. Keep server or cluster announcements and impersonation indicators +in the page. + ### Dependent operations Show a blocked prerequisite beside the resource that needs it. Put the @@ -148,6 +165,12 @@ the source and destination, show the snapshot totals first, and put the per-folder or per-item breakdown below. Label partial counts and missing estimates explicitly. Distinguish the full source inventory from work remaining after a checkpoint. Do not display credentials or source content. +Distinguish a matching existing account from a requested new account by +name and domain. Show new-account settings only for that choice when +JavaScript is available, and validate both paths on the server. Keep +the selected destination visible while a job is queued. Results separate +completed, unconfirmed, and unrequested work, with links to review or finish +setup. For selective imports, put editable choices below the inventory and keep them outside auto-refreshing status regions. State explicitly which choices affect the destination, which are skipped and whether failures can leave diff --git a/src/coulobre/hosting/directadmin_web_import.py b/src/coulobre/hosting/directadmin_web_import.py index 33ed2de..d0727cc 100644 --- a/src/coulobre/hosting/directadmin_web_import.py +++ b/src/coulobre/hosting/directadmin_web_import.py @@ -1,7 +1,9 @@ """Stage and inspect DirectAdmin archives for operator approval.""" +import errno import fcntl import hashlib +import logging import os import stat from datetime import timedelta @@ -146,9 +148,19 @@ def register_upload(upload, actor): except Exception: path.unlink(missing_ok=True) raise - except OSError: + except OSError as error: + logging.getLogger(__name__).warning( + "DirectAdmin archive staging failed (errno %s).", error.errno + ) + if error.errno in {errno.ENOSPC, errno.EDQUOT}: + detail = "Free space in the panel's import storage and try again." + else: + detail = ( + "Check the panel service's private import storage. " + "Inspect its StateDirectory and journal before retrying." + ) raise ValidationError( - "Could not stage the archive. Check server storage." + f"Could not stage the archive. {detail}" ) from None return job @@ -540,7 +552,10 @@ def confirm_import(job_id, actor, selection): validate_extra_domains(selection, account, job.report) plan = plan_for_import(account, selection) validate_quotas(job.report, account, selection, plan) - job.selection = selection | {"account_id": getattr(account, "pk", None)} + job.selection = selection | { + "account_id": getattr(account, "pk", None), + "destination_name": account.name if account else selection["name"], + } job.state = "import_queued" job.confirmed_by = actor job.started_at = None diff --git a/src/coulobre/hosting/directadmin_web_tasks.py b/src/coulobre/hosting/directadmin_web_tasks.py index 008903b..0a8f62e 100644 --- a/src/coulobre/hosting/directadmin_web_tasks.py +++ b/src/coulobre/hosting/directadmin_web_tasks.py @@ -271,13 +271,20 @@ def restore_components(job): f"{item['label']} is no longer provisioned." ) if item["kind"] != "mail" or item["messages"]: - restore_directadmin_component( + receipt = restore_directadmin_component( item["kind"], destination_spec(job, item), archive_path(job.pk), source=item.get("source", ""), digest=job.digest, ) + if isinstance(receipt, dict): + item["receipt"] = { + field: receipt[field] + for field in ("files", "bytes", "messages") + if type(receipt.get(field)) is int + and receipt[field] >= 0 + } item["status"] = ( "Mailbox configured (no source messages)" if item["kind"] == "mail" and not item["messages"] diff --git a/src/coulobre/hosting/directadmin_web_views.py b/src/coulobre/hosting/directadmin_web_views.py index a540b3e..6f87a36 100644 --- a/src/coulobre/hosting/directadmin_web_views.py +++ b/src/coulobre/hosting/directadmin_web_views.py @@ -1,4 +1,5 @@ from django import forms +from django.contrib import messages from django.core.exceptions import ValidationError from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone @@ -37,6 +38,8 @@ class DirectAdminSelectionForm(forms.Form): ) target = forms.ChoiceField( label="Destination", + widget=forms.RadioSelect, + initial="new", choices=( ("new", "Create a hosting account"), ("existing", "Use the matching empty hosting account"), @@ -78,6 +81,13 @@ class DirectAdminSelectionForm(forms.Form): def __init__(self, report, *args, **kwargs): super().__init__(*args, **kwargs) self.report = report + if ( + self.is_bound + and self.data.get(self.add_prefix("target")) == "existing" + ): + self.data = self.data.copy() + for field in ("hosting_plan", "name"): + self.data.pop(self.add_prefix(field), None) choices = [ (entry["name"], entry["name"]) for entry in report["domains"] ] @@ -131,7 +141,11 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): except ValidationError as error: form.add_error("archive", error) else: + messages.success(request, "DirectAdmin preflight queued.") return redirect("panel:directadmin_import", pk=job.pk) + messages.error( + request, "Preflight not queued. Check the upload below." + ) return self.page(form=form, status=400) job = get_object_or_404(DirectAdminWebImport, pk=pk) @@ -146,6 +160,7 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): report={}, ): archive_path(pk).unlink(missing_ok=True) + messages.info(request, "DirectAdmin upload discarded.") return redirect("panel:directadmin_import", pk=pk) form = DirectAdminSelectionForm(job.report, request.POST) if form.is_valid(): @@ -154,7 +169,11 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): except ValidationError as error: form.add_error(None, error) else: + messages.success(request, "DirectAdmin import queued.") return redirect("panel:directadmin_import", pk=pk) + messages.error( + request, "Import not queued. Review the highlighted details." + ) return self.page(job, form, status=400) def page(self, job=None, form=None, status=200): @@ -163,12 +182,24 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): form = DirectAdminArchiveForm() elif job.state == "review" and job.expires_at > timezone.now(): form = DirectAdminSelectionForm(job.report) + components = set(job.selection.get("components", ())) if job else set() + choices = DirectAdminSelectionForm.base_fields["components"].choices return render( self.request, self.template_name, { "job": job, "form": form, + "not_started": [ + label for key, label in choices if key in components + ] + if job and job.finished_at and not job.work + else (), + "not_selected": [ + label + for key, label in choices + if components and key not in components + ], "pending": job is not None and job.state in ACTIVE_STATES, "recent": DirectAdminWebImport.objects.select_related( "account" diff --git a/src/coulobre/hosting/static/hosting/directadmin-import.js b/src/coulobre/hosting/static/hosting/directadmin-import.js new file mode 100644 index 0000000..ba255de --- /dev/null +++ b/src/coulobre/hosting/static/hosting/directadmin-import.js @@ -0,0 +1,22 @@ +"use strict"; + +const importForm = document.querySelector("[data-directadmin-review]"); + +if (importForm) { + const domain = importForm.elements.domain; + const destination = importForm.elements.target; + const newFields = importForm.querySelector("[data-import-new]"); + const matches = [...importForm.querySelectorAll("[data-import-match]")]; + + function updateDestination() { + const existing = destination.value === "existing"; + newFields.hidden = existing; + newFields.disabled = existing; + for (const match of matches) { + match.hidden = !existing || match.dataset.importMatch !== domain.value; + } + } + + importForm.addEventListener("change", updateDestination); + updateDestination(); +} diff --git a/src/coulobre/hosting/static/hosting/panel-live-status.js b/src/coulobre/hosting/static/hosting/panel-live-status.js index fab3f1a..501603e 100644 --- a/src/coulobre/hosting/static/hosting/panel-live-status.js +++ b/src/coulobre/hosting/static/hosting/panel-live-status.js @@ -43,6 +43,18 @@ async function refreshStatus() { for (const detail of next.querySelectorAll("details[data-live-detail]")) { detail.open = openDetails.has(detail.dataset.liveDetail); } + const stateChanged = region.dataset.liveState !== next.dataset.liveState; + if (next.dataset.liveState) { + region.dataset.liveState = next.dataset.liveState; + } + if (stateChanged && next.dataset.liveNotice) { + document.dispatchEvent(new CustomEvent("coulobre:status-changed", { + detail: { + message: next.dataset.liveNotice, + level: next.dataset.liveNoticeLevel || "info", + }, + })); + } if (region.innerHTML === next.innerHTML) { continue; } diff --git a/src/coulobre/hosting/static/hosting/panel-notifications.js b/src/coulobre/hosting/static/hosting/panel-notifications.js new file mode 100644 index 0000000..d0bb078 --- /dev/null +++ b/src/coulobre/hosting/static/hosting/panel-notifications.js @@ -0,0 +1,37 @@ +"use strict"; + +const notificationStack = document.querySelector("[data-panel-notifications]"); + +if (notificationStack) { + notificationStack.classList.add("panel-notifications-floating"); + + function enhanceNotification(notice) { + const dismiss = document.createElement("button"); + dismiss.type = "button"; + dismiss.className = "button secondary compact"; + dismiss.textContent = "Dismiss"; + dismiss.setAttribute("aria-label", "Dismiss notification"); + dismiss.addEventListener("click", () => { + const next = notice.nextElementSibling || notice.previousElementSibling; + notice.remove(); + (next?.querySelector("button") || document.getElementById("main-content")).focus(); + }); + notice.append(dismiss); + } + + notificationStack.querySelectorAll(".panel-notification").forEach(enhanceNotification); + + document.addEventListener("coulobre:status-changed", event => { + const {message, level} = event.detail; + const notice = document.createElement("div"); + notice.className = "notice panel-notification"; + notice.dataset.notificationLevel = level; + const content = document.createElement("p"); + content.setAttribute("role", level === "error" ? "alert" : "status"); + notice.append(content); + enhanceNotification(notice); + notificationStack.append(notice); + // Add the text after the live region is mounted. + requestAnimationFrame(() => { content.textContent = message; }); + }); +} diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index a0aea73..9ff9932 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -719,16 +719,13 @@ h3, h4, h5, h6 { flex: 1 1 25rem; } -.account-identity { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0.15rem 0.65rem; +.account-identity, .cell-primary-domain { + overflow-wrap: anywhere; } -.account-identity > * { - min-width: 0; - overflow-wrap: anywhere; +th.cell-primary-domain, td.cell-primary-domain { + text-align: end; + width: 22%; } .account-heading-meta { @@ -838,6 +835,7 @@ input::placeholder { } .table-scroll { + position: relative; overflow-x: auto; } @@ -1595,3 +1593,50 @@ fieldset > div:has(> div > label > input:is([type="checkbox"], [type="radio"])) min-inline-size: 0; grid-template-rows: auto auto 1fr auto; } + +.panel-notifications:not(:has(.panel-notification)) { + display: none; +} + +.panel-notifications-floating { + position: fixed; + inset-block-start: 1rem; + inset-inline-end: 1rem; + width: min(27rem, calc(100vw - 2rem)); + max-height: 45vh; + overflow: auto; + z-index: 20; + display: grid; + gap: 0.45rem; +} + +.panel-notification { + display: flex; + align-items: start; + justify-content: space-between; + gap: 0.75rem; + overflow-wrap: anywhere; +} + +.panel-notifications-floating .panel-notification { + margin: 0; + border-radius: 0.4rem; + padding: 0.65rem 0.8rem; +} + +.panel-notification p { + margin: 0; +} + +.panel-notification[data-notification-level="error"] { + border-color: var(--invalid); + background-color: var(--error-bg); +} + +.panel-notification[data-notification-level="warning"] { + background-color: var(--warning-bg); +} + +[data-import-new][hidden] { + display: none; +} diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index ee37539..93a1d99 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -35,7 +35,7 @@ {% endif %} -
Type the primary domain to confirm this preview.
{% csrf_token %} {{ form.as_div }} - + {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index d0dc29f..d0c1a65 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -93,10 +93,14 @@ {% endif %} {% for announcement in panel_announcements %}| Account | Hosting node | Status | ||||
|---|---|---|---|---|---|---|
| Account | Hosting node | Primary domain | Status | |||
| {% include "hosting/account_identity.html" with account_url=account.url name=account.name primary_domain=account.primary_domain only %} | +{% include "hosting/account_identity.html" with account_url=account.url name=account.name only %} | {% include "hosting/hosting_node.html" with node=page.node only %} | + {% include "hosting/account_primary_domain.html" with name=account.name primary_domain=account.primary_domain only %}{% include "hosting/account_status.html" %} | |||
| No matching accounts on {{ page.node.label }}{% if previous_offset is not None %} on this page{% endif %}. | +No matching accounts on {{ page.node.label }}{% if previous_offset is not None %} on this page{% endif %}. | |||||
| View all results on {{ page.node.label }} | ||||||
| View all results on {{ page.node.label }} | ||||||
| Requested | Destination | Status | |||
|---|---|---|---|---|---|
| Requested | Destination | Status | Actions | ||
| {{ previous.requested_at|date:"j M Y, H:i T" }} | -{{ previous.account|default:"Not selected" }} | +{{ previous.requested_at|date:"j M Y, H:i T" }} | ++ {% if previous.selection.domain %} + {{ previous.selection.domain }}{% if previous.selection.destination_name and previous.selection.destination_name != previous.selection.domain %} · {{ previous.selection.destination_name }}{% endif %} + {% else %}Not selected{% endif %} + | {{ previous.get_state_display }} | ++ {% if previous.state == "review" %}Review preflight{% elif previous.finished_at %}View import result{% else %}View import progress{% endif %} + |
Destination · {{ job.selection.domain }}{% if job.selection.destination_name and job.selection.destination_name != job.selection.domain %} · {{ job.selection.destination_name }}{% endif %}
+ {% endif %} {% if pending %}{% if job.state == "inspect_queued" or job.state == "inspecting" %} @@ -56,17 +76,21 @@ {% if job.work %}
Changes already applied are not undone. Check the destination and the component status below.
{% endif %} {% elif job.state == "complete" %}Review the imported data before updating DNS. Existing public DNS and the source account were not changed.
+ {% if "dns" in job.selection.components and job.account %}{% endif %} {% endif %} {% if job.work %}| Component | Destination | State |
|---|---|---|
| {{ item.kind|capfirst }} | {{ item.label }} | {{ item.status|default:"Waiting" }} |
| {{ item.kind|capfirst }} | {{ item.label }} | {% if item.status %}{{ item.status }}{% elif job.finished_at %}Not completed{% else %}Waiting{% endif %}
+ {% if item.receipt %} {% if "files" in item.receipt %}{{ item.receipt.files }} files{% elif "messages" in item.receipt %}{{ item.receipt.messages }} messages{% endif %}{% if "bytes" in item.receipt %}{% if "files" in item.receipt or "messages" in item.receipt %} · {% endif %}{{ item.receipt.bytes|filesizeformat }}{% endif %} {% endif %} |
Not started · {{ not_started|join:", " }}
{% endif %} + {% if not_selected and job.finished_at %}Not requested · {{ not_selected|join:", " }}
{% endif %}Source account {{ job.report.username }} · {{ job.size|filesizeformat }} upload. Choose a primary domain and any additional domains to restore. Database dumps belong to the whole source account.
{% for domain in job.report.domains %}Some database dumps have unsupported names or are empty or duplicated. They are not imported.
{% endif %} {% if job.report.home_archive %}Nested home archives are not imported.
{% endif %} - {% if job.report.skipped_non_regular_entries %}The archive contains {{ job.report.skipped_non_regular_entries }} links or special entries. Selected website or mail files containing unsupported entries may be rejected.
{% endif %} + {% if job.report.skipped_non_regular_entries %}The archive contains unsupported links or special entries ({{ job.report.skipped_non_regular_entries }}). Website or mail components containing them may be rejected.
{% endif %}{{ topology.problem }}
{% endif %}{{ problem }}
{% endif %} {% if not job or job.problem and not job.remove %} -Checking the source and destination. Nothing is being copied.
diff --git a/src/coulobre/hosting/templates/hosting/operator_backups.html b/src/coulobre/hosting/templates/hosting/operator_backups.html index fe6e1c2..346f13c 100644 --- a/src/coulobre/hosting/templates/hosting/operator_backups.html +++ b/src/coulobre/hosting/templates/hosting/operator_backups.html @@ -24,7 +24,7 @@ {% if enabled %}{{ message }}
+The archive contains local service configuration, MariaDB, and hosted files and mail. Retrieve it on the server using an administrator account.
Enable system backups and the local operator worker on this server.
{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/website_files.html b/src/coulobre/hosting/templates/hosting/website_files.html index 448e522..4ad9686 100644 --- a/src/coulobre/hosting/templates/hosting/website_files.html +++ b/src/coulobre/hosting/templates/hosting/website_files.html @@ -25,13 +25,13 @@ {% csrf_token %} {{ upload_form.as_div }} - +{{ message }}
- {% endfor %} - {% endif %} {% block page_content %}{% endblock %} {% endblock %} diff --git a/src/coulobre/hosting/test_directadmin_web_import.py b/src/coulobre/hosting/test_directadmin_web_import.py index 1cb0cf5..761560e 100644 --- a/src/coulobre/hosting/test_directadmin_web_import.py +++ b/src/coulobre/hosting/test_directadmin_web_import.py @@ -139,7 +139,7 @@ class DirectAdminWebImportTests(TestCase): response = self.client.get(url) self.assertContains(response, "source_main") self.assertContains(response, "info@example.net") - self.assertContains(response, "1 messages") + self.assertContains(response, "1 message · 1 folder with messages") self.assertContains(response, "6 DNS records") self.assertNotContains(response, "should-never-be-stored") self.assertNotIn("should-never-be-stored", str(job.report)) @@ -156,7 +156,16 @@ class DirectAdminWebImportTests(TestCase): name="Destination", primary_domain=DOMAIN ) job, url = self.prepare() - self.assertEqual(self.submit(url, target="existing").status_code, 302) + review = self.client.get(url) + self.assertContains(review, "Use the matching empty hosting account") + self.assertContains(review, "New account settings") + response = self.submit( + url, target="existing", hosting_plan="invalid", name="unused" + ) + self.assertEqual(response.status_code, 302) + queued = self.client.get(self.url) + self.assertContains(queued, "Destination") + self.assertContains(queued, "View import progress") run_directadmin_import(str(job.pk), "import_queued") job.refresh_from_db() self.assertEqual(job.state, "provisioning", job.problem) @@ -170,6 +179,20 @@ class DirectAdminWebImportTests(TestCase): self.assertFalse(archive_path(job.pk).exists()) self.assertFalse(HostingDatabase.objects.exists()) self.assertFalse(HostingMailbox.objects.exists()) + self.assertContains(self.client.get(self.url), "View import result") + self.assertContains(self.client.get(url), "Not requested") + + def test_status_poll_does_not_consume_the_submission_notification(self): + _, url = self.prepare() + self.assertEqual(self.submit(url).status_code, 302) + self.assertNotContains( + self.client.get(url, headers={"X-Coulobre-Status": "1"}), + "DirectAdmin import queued.", + ) + self.assertContains(self.client.get(url), "DirectAdmin import queued.") + self.assertNotContains( + self.client.get(url), "DirectAdmin import queued." + ) def test_rejects_nonempty_target_on_review_or_after_confirmation(self): account = HostingAccount.objects.create( diff --git a/src/coulobre/hosting/test_package_workflows.py b/src/coulobre/hosting/test_package_workflows.py index 4629e21..0a3244f 100644 --- a/src/coulobre/hosting/test_package_workflows.py +++ b/src/coulobre/hosting/test_package_workflows.py @@ -123,5 +123,10 @@ class PackageWorkflowTests(TestCase): ) response = self.client.get(reverse("panel:accounts")) self.assertContains(response, 'class="account-identity"', count=2) - self.assertNotContains(response, ">same.example") - self.assertContains(response, ">different.example") + self.assertContains(response, "Same as account name", count=1) + self.assertContains(response, "different.example", count=1) + self.assertContains(response, "Primary domain") + self.assertLess( + response.content.index(b">Primary domain<"), + response.content.index(b">Status<"), + )