Przeglądaj źródła

Implementierung von Rückkehr-URLs und Fokusverwaltung für Detailansichten

Verbesserung der Navigation und Benutzererfahrung durch dynamische Filterung und Statusanzeigen in der Liste; Anpassungen an den Templates und CSS für bessere Lesbarkeit und Interaktivität.
gc-server3 2 tygodni temu
rodzic
commit
996210f053

+ 16 - 0
README.md

@@ -143,3 +143,19 @@ Die Fußleiste zeigt Anzahl und offenen Gesamtbetrag aller gefilterten Treffer,
 von den bereits nachgeladenen Zeilen. Aktive Filter lassen sich dort aufklappen.
 Auch ohne Treffer bleiben die Filter bedienbar. Die gemeinsamen Gestaltungsregeln liegen
 in `app.css`, die Ansichten ergänzen `list.css` beziehungsweise `details.css`.
+
+## Rückkehr aus der Detailseite und erneute Anmeldung
+
+„Zurück“, „Speichern & Zurück“ und Browser-Zurück laden die Liste frisch, behalten die
+Filter und führen zur zuvor geöffneten Rechnung. Dazu wird auf der Detailseite eine
+validierte Listenadresse in `return_to` und auf der Liste die Belegkennung in `focus`
+mitgeführt. Liegt der Beleg hinter dem ersten Nachladeblock, liefert der erste Aufruf
+die Zeilen bis einschließlich seines Blocks; danach läuft das Nachladen normal weiter.
+Ist der Beleg nicht mehr enthalten, bleiben die Filter bestehen und ein Hinweis erscheint.
+Der Browser hält Rückkehrkontexte getrennt je Tab und Benutzer; es werden keine
+Kommentare oder Formulareingaben im Browserspeicher abgelegt.
+
+Bei abgelaufener Anmeldung führen HTMX-Anfragen nach dem Login auf die vollständige
+gefilterte Liste beziehungsweise Detailseite. Kommentar- und Buchungsfragmente sowie
+technische Nachladeseiten sind keine Login-Rücksprungziele. Unterbrochene Schreibaktionen
+werden nicht automatisch wiederholt; ungespeicherte Eingaben werden nicht gesichert.

+ 3 - 3
app/auth.py

@@ -16,6 +16,7 @@ from .oauth_token import (
     renew_access_token,
     token_needs_renewal,
 )
+from .navigation import normalize_page_url
 from .permissions import Principal, highest_role, load_entitlements
 
 logger = logging.getLogger(__name__)
@@ -47,9 +48,7 @@ def clear_session_cookie(response) -> None:
 
 
 def safe_next_url(value: str | None, default: str = "/select") -> str:
-    if not value or not value.startswith("/") or value.startswith("//") or "\\" in value:
-        return default
-    return value
+    return normalize_page_url(value, default)
 
 
 def _principal(payload: dict, entitlements) -> Principal:
@@ -135,6 +134,7 @@ class AuthenticationMiddleware(BaseHTTPMiddleware):
             next_url = request.url.path
             if request.url.query:
                 next_url += "?" + request.url.query
+            next_url = normalize_page_url(next_url, current_url=request.headers.get("HX-Current-URL"))
             login_url = f"/login?next={quote(next_url, safe='')}"
             if request.headers.get("HX-Request", "").lower() == "true":
                 response = Response(status_code=200, headers={"HX-Redirect": login_url})

+ 105 - 0
app/navigation.py

@@ -0,0 +1,105 @@
+"""Canonical page URLs for return navigation and authentication recovery."""
+import re
+from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit
+
+from .query_filter import import_filter_config
+
+LIST_PATH = '/app/forderungen/liste'
+DETAIL_PREFIX = '/app/forderungen/details/'
+DETAIL_PAGE = re.compile(r'^/app/forderungen/details/([^/]+)(?:/(?:kommentare|buchungen))?/?$')
+
+
+def valid_focus(value: str | None) -> bool:
+    if not value or any(ord(c) < 32 or ord(c) == 127 or c in '/\\' for c in value):
+        return False
+    tenant, separator, number = value.partition('_')
+    return bool(separator and tenant and number and len(tenant) <= 20 and len(number) <= 100)
+
+
+def _local_parts(value):
+    if not isinstance(value, str) or not value.startswith('/') or value.startswith('//'):
+        return None
+    if any(ord(c) < 32 or ord(c) == 127 or c == '\\' for c in value):
+        return None
+    try:
+        parts = urlsplit(value)
+    except ValueError:
+        return None
+    decoded = unquote(parts.path)
+    if parts.scheme or parts.netloc or decoded.startswith('//') or '\\' in decoded:
+        return None
+    if any(ord(c) < 32 or ord(c) == 127 for c in decoded):
+        return None
+    return parts
+
+
+def list_url(filters=None, focus: str | None = None) -> str:
+    filters = filters or {}
+    params = {f.name: filters[f.name] for f in import_filter_config('forderungen')
+              if f.name in filters and filters[f.name] not in ('', None)}
+    if valid_focus(focus):
+        params['focus'] = focus
+    return LIST_PATH + ('?' + urlencode(params) if params else '')
+
+
+def list_return_url(value: str | None, primary_key: str) -> str:
+    parts = _local_parts(value)
+    filters = dict(parse_qsl(parts.query)) if parts and parts.path == LIST_PATH else {}
+    return list_url(filters, primary_key)
+
+
+def _current_parts(value):
+    """Extract context, never a redirect origin, from the browser's current URL."""
+    if not value:
+        return None
+    try:
+        parts = urlsplit(value)
+    except ValueError:
+        return None
+    if parts.scheme and parts.scheme not in ('http', 'https'):
+        return None
+    return _local_parts(parts.path + ('?' + parts.query if parts.query else ''))
+
+
+def return_url_for_request(request, primary_key: str, explicit: str | None = None) -> str:
+    value = explicit if explicit is not None else request.query_params.get('return_to')
+    if value is None:
+        current = _current_parts(request.headers.get('HX-Current-URL'))
+        match = DETAIL_PAGE.fullmatch(unquote(current.path)) if current else None
+        if match and match[1] == primary_key:
+            value = dict(parse_qsl(current.query)).get('return_to')
+    return list_return_url(value, primary_key)
+
+
+def detail_navigation_context(request, primary_key: str, explicit: str | None = None) -> dict:
+    return_url = return_url_for_request(request, primary_key, explicit)
+    return {
+        'return_url': return_url,
+        'detail_post_url': DETAIL_PREFIX + quote(primary_key, safe='') + '?' + urlencode({'return_to': return_url}),
+    }
+
+
+def normalize_page_url(value: str | None, default='/select', current_url: str | None = None) -> str:
+    parts = _local_parts(value)
+    if not parts:
+        return default
+    params = dict(parse_qsl(parts.query))
+    current = _current_parts(current_url)
+    if parts.path == LIST_PATH:
+        focus = params.get('focus')
+        if not focus and current and current.path == LIST_PATH:
+            previous = dict(parse_qsl(current.query))
+            if list_url(params) == list_url(previous):
+                focus = previous.get('focus')
+        return list_url(params, focus)
+    match = DETAIL_PAGE.fullmatch(unquote(parts.path))
+    if match and valid_focus(match[1]):
+        primary_key = match[1]
+        value = params.get('return_to')
+        if value is None and current:
+            previous = DETAIL_PAGE.fullmatch(unquote(current.path))
+            if previous and previous[1] == primary_key:
+                value = dict(parse_qsl(current.query)).get('return_to')
+        detail = DETAIL_PREFIX + quote(primary_key, safe='')
+        return detail + ('?' + urlencode({'return_to': list_return_url(value, primary_key)}) if value else '')
+    return parts.path + ('?' + parts.query if parts.query else '') + ('#' + parts.fragment if parts.fragment else '')

+ 32 - 6
app/routes.py

@@ -29,6 +29,7 @@ from .forderung_history import HistoryScope, history_context, section_context
 from .forderung_summary import get_forderung_summary
 from .jinja_templates import templates
 from .ldap import DirectoryUnavailable, DirectoryUser, ldap_authenticate, normalize_username
+from .navigation import detail_navigation_context, list_url, return_url_for_request, valid_focus
 from .oauth_token import create_access_token
 from .permissions import (
     current_principal,
@@ -153,7 +154,7 @@ def select_get(request: Request):
 
 
 @router.get("/app/forderungen/liste", response_class=HTMLResponse)
-def forderungen_liste(request: Request, db: Session = Depends(get_session), limit: int = 100, page: int = 0):
+def forderungen_liste(request: Request, db: Session = Depends(get_session), limit: int = 100, page: int = 0, focus: str | None = None):
     principal = current_principal(request)
     forderung_filter_config = import_filter_config("forderungen")
 
@@ -162,8 +163,12 @@ def forderungen_liste(request: Request, db: Session = Depends(get_session), limi
         for f in forderung_filter_config
         if request.query_params.get(f.name, "") != ""
     }
-    if page == 0 and len(params) < len(request.query_params):
-        return RedirectResponse(url="/app/forderungen/liste?" + urlencode(params))
+    if not valid_focus(focus):
+        focus = None
+    if page == 0:
+        canonical = list_url(params, focus)
+        if request.url.path + ('?' + request.url.query if request.url.query else '') != canonical:
+            return RedirectResponse(url=canonical)
 
     query_clauses = []
     query_values = {"auth_username": principal.username}
@@ -212,7 +217,16 @@ def forderungen_liste(request: Request, db: Session = Depends(get_session), limi
         "Anzahl": len(q),
     }
 
-    q_limit = q[page * limit : (page + 1) * limit]
+    end = (page + 1) * limit
+    focus_found = False
+    if page == 0 and focus:
+        tenant_column, number_column = col_names.index('Client_DB'), col_names.index('Beleg_Nr')
+        for index, row in enumerate(q):
+            if f"{row[tenant_column]}_{row[number_column]}" == focus:
+                end = max(end, (index // limit + 1) * limit)
+                focus_found = True
+                break
+    q_limit = q[page * limit : end]
 
     defaults = {}
     for f in forderung_filter_config:
@@ -237,9 +251,14 @@ def forderungen_liste(request: Request, db: Session = Depends(get_session), limi
             "summary": summary,
             "page": page,
             "limit": limit,
-            "has_more": (page + 1) * limit < len(q),
+            "has_more": end < len(q),
+            "next_page": end // limit,
+            "list_url": list_url(params),
+            "focus": focus if page == 0 else None,
+            "focus_missing": bool(page == 0 and focus and not focus_found),
             "filter_config": forderung_filter_config,
         },
+        headers={"Cache-Control": "no-store"},
     )
 
 
@@ -249,8 +268,10 @@ def forderungen_details(request: Request, primary_key: str, db: Session = Depend
     pkey = convert_primary_key("forderungen", primary_key)
     if not has_forderung_access(db, principal, pkey["Client_DB"], pkey["Beleg_Nr"]):
         context = get_forderung_summary(db, pkey["Client_DB"], pkey["Beleg_Nr"])
+        context["return_url"] = return_url_for_request(request, primary_key)
         return templates.TemplateResponse(request, "forderungen/details/notice.html", context)
     template_context = get_template_context(request, pkey, db)
+    template_context.update(detail_navigation_context(request, primary_key))
     return templates.TemplateResponse(request, "forderungen/details/details.html", template_context)
 
 
@@ -300,6 +321,7 @@ async def post_forderungen_details(
     primary_key: str,
     source: Annotated[str, Form()],
     redirect: Annotated[str | None, Form()] = None,
+    return_to: Annotated[str | None, Form()] = None,
     comment_scope: Annotated[HistoryScope, Form()] = "invoice",
     db: Session = Depends(get_session),
 ):
@@ -358,12 +380,16 @@ async def post_forderungen_details(
             db.execute(text(subquery), data)
     db.commit()
 
+    return_url = return_url_for_request(request, primary_key, return_to if return_to is not None else redirect)
     if redirect:
-        return RedirectResponse(url=redirect, status_code=302)
+        if request.headers.get('HX-Request', '').lower() == 'true':
+            return HTMLResponse('', headers={'HX-Redirect': return_url})
+        return RedirectResponse(url=return_url, status_code=303)
     if source == "comments":
         context = history_context(db, pkey, "kommentare", comment_scope)
         return templates.TemplateResponse(request, "forderungen/details/details_kommentare.html", context)
     template_context = get_template_context(request, pkey, db)
+    template_context.update(detail_navigation_context(request, primary_key, return_url))
     return templates.TemplateResponse(request, "forderungen/details/details_formular.html", template_context)
 
 

+ 3 - 0
static/assets/css/list.css

@@ -27,6 +27,9 @@ body:has(.gc-list-page) { max-width: 1840px; }
 .gc-list-table th { background: var(--gc-brand-action); color: #101b24; font-size: 1rem; font-weight: 700; border-bottom: 1px solid #526b7e; line-height: 1.45; hyphens: auto; }
 .gc-list-table tbody td { background: #fff; border-bottom: 1px solid #e5e9ed; line-height: 1.5; }
 .gc-list-table .gc-invoice-row:hover td { background: #f6f8fa; }
+.gc-list-table .gc-invoice-row.gc-return-highlight td { background: #dfeaf1; }
+.gc-list-table .gc-invoice-row:focus-visible { outline: 3px solid #354f63; outline-offset: -3px; }
+.gc-return-status { padding: .85rem 1rem; margin: 0; border: 1px solid #b1bcc7; border-radius: 6px; background: #edf2f5; }
 .gc-list-table th:nth-child(1) { width: 8%; }
 .gc-list-table th:nth-child(2) { width: 9%; }
 .gc-list-table th:nth-child(3) { width: 10%; }

+ 79 - 0
static/assets/js/navigation.js

@@ -0,0 +1,79 @@
+/* Return state is per tab and user; only URLs and invoice keys are stored. */
+(() => {
+  const listPath = '/app/forderungen/liste';
+  let memory;
+  const processed = new WeakSet();
+  const storageKey = () => `gc-list-return:${document.body.dataset.gcUser || ''}`;
+  const canonical = value => {
+    const url = new URL(value, location.origin);
+    url.searchParams.delete('focus');
+    url.searchParams.delete('page');
+    url.searchParams.delete('limit');
+    url.searchParams.sort();
+    return url.pathname + url.search;
+  };
+  const read = () => {
+    try { return JSON.parse(sessionStorage.getItem(storageKey())) || memory; }
+    catch { return memory; }
+  };
+  const clear = () => {
+    memory = undefined;
+    try { sessionStorage.removeItem(storageKey()); } catch { /* Storage can be disabled. */ }
+  };
+  function remember(value) {
+    if (!value) return;
+    const url = new URL(value, location.origin);
+    if (url.origin !== location.origin || url.pathname !== listPath) return;
+    memory = { returnUrl: url.pathname + url.search, listUrl: canonical(url), user: document.body.dataset.gcUser || '' };
+    try { sessionStorage.setItem(storageKey(), JSON.stringify(memory)); } catch { /* Use document memory. */ }
+  }
+  function refreshReturn(event) {
+    if (location.pathname !== listPath) return false;
+    const state = read();
+    if (!state || state.user !== (document.body.dataset.gcUser || '') || state.listUrl !== canonical(location.href)) return false;
+    // Do not let HTMX paint an old history snapshot before the fresh GET.
+    event?.stopImmediatePropagation();
+    const url = new URL(state.returnUrl, location.origin);
+    if (url.origin !== location.origin || url.pathname !== listPath) { clear(); return false; }
+    location.replace(url.pathname + url.search);
+    return true;
+  }
+  async function initialize() {
+    const back = document.querySelector('[data-gc-return-url]');
+    if (back) remember(back.dataset.gcReturnUrl);
+    const state = document.getElementById('gc-list-state');
+    if (!state || processed.has(state)) return;
+    processed.add(state);
+    const focus = state.dataset.focus;
+    if (!focus) return;
+    clear();
+    const row = [...document.querySelectorAll('.gc-invoice-row[data-primary-key]')]
+      .find(node => node.dataset.primaryKey === focus);
+    if (!row) return;
+    await Promise.race([document.fonts?.ready, new Promise(resolve => setTimeout(resolve, 500))]);
+    await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+    if (!row.isConnected) return;
+    const top = (document.querySelector('.gc-app-header')?.offsetHeight || 0)
+      + (document.querySelector('#invoice-list thead')?.offsetHeight || 0) + 16;
+    const bottom = (document.querySelector('.gc-list-summary')?.offsetHeight || 0) + 16;
+    const rect = row.getBoundingClientRect();
+    row.focus({ preventScroll: true });
+    window.scrollTo({ top: Math.max(0, scrollY + rect.top - top - Math.max(0, (innerHeight - top - bottom - rect.height) / 2)), behavior: 'instant' });
+    row.classList.add('gc-return-highlight');
+    setTimeout(() => row.classList.remove('gc-return-highlight'), 3000);
+  }
+  document.addEventListener('click', event => {
+    const link = event.target.closest('[data-gc-detail-link]');
+    // New tabs receive their own return_to URL; leave this tab's state alone.
+    if (link && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && link.target !== '_blank') remember(link.dataset.returnUrl);
+  });
+  window.addEventListener('popstate', refreshReturn, { capture: true });
+  window.addEventListener('pageshow', event => {
+    if (!event.persisted || !refreshReturn(event)) initialize();
+  });
+  document.addEventListener('DOMContentLoaded', initialize);
+  document.addEventListener('htmx:load', initialize);
+  document.addEventListener('htmx:historyRestore', event => {
+    if (!refreshReturn(event)) initialize();
+  }, { capture: true });
+})();

+ 2 - 1
templates/base/base.html

@@ -28,6 +28,7 @@
 
   <link href="/static/assets/css/details.css" rel="stylesheet">
   <link href="/static/assets/css/list.css" rel="stylesheet">
+  <script src="/static/assets/js/navigation.js" defer></script>
   <script src="/static/assets/js/list.js" defer></script>
   <script src="/static/assets/js/layout.js" defer></script>
 
@@ -35,7 +36,7 @@
   <link rel="icon" href="/static/assets/images/favicon.ico" type="image/x-icon">
 </head>
 
-<body class="container" hx-boost="true" hx-headers='{"X-CSRF-Token": "{{ request.state.principal.csrf }}"}'>
+<body class="container" data-gc-user="{{ request.state.principal.username }}" hx-boost="true" hx-headers='{"X-CSRF-Token": "{{ request.state.principal.csrf }}"}'>
   <div class="wrapper d-flex flex-column min-vh-100">
     <header class="header gc-app-header">
       <div class="container-fluid gc-header-inner">

+ 1 - 1
templates/base/chat_container.html

@@ -5,7 +5,7 @@
     {% include 'forderungen/details/details_kommentare.html' %}
     <div class="input-area">
         <div class="toolbar">
-            <form id="comment-form" method="post" action="{{ detail_url }}" hx-post="{{ detail_url }}"
+            <form id="comment-form" method="post" action="{{ detail_post_url|default(detail_url) }}" hx-post="{{ detail_post_url|default(detail_url) }}"
                 hx-target="#comments-history" hx-swap="outerHTML" hx-push-url="false"
                 hx-sync="#comments-history:replace"
                 hx-disabled-elt="#comment-form input, #comment-form button, #comments-history button"

+ 4 - 0
templates/base/liste.html

@@ -1,7 +1,11 @@
 {% extends "base/base.html" %}
 {% block page_class %}gc-list-page{% endblock %}
 {% block content %}
+<div id="gc-list-state" data-list-url="{{ list_url }}" data-focus="{{ focus or '' }}" hidden></div>
 <h1>Forderungen</h1>
+{% if focus_missing %}
+<p class="gc-return-status" role="status">Die zuvor geöffnete Rechnung ist in der aktualisierten Ergebnisliste nicht mehr enthalten. Ihre Filter wurden beibehalten.</p>
+{% endif %}
 <section class="gc-card" aria-labelledby="list-filter-title">
   <h2 class="gc-section-title" id="list-filter-title"><i class="icon cil-filter" aria-hidden="true"></i> Filter</h2>
   <div class="gc-list-filter-content">{% include 'base/liste_filter.html' %}</div>

+ 1 - 1
templates/base/liste_tabelle.html

@@ -7,7 +7,7 @@
 {% endfor %}
 {% if has_more %}
 <tr class="gc-list-load" hx-trigger="revealed" hx-swap="outerHTML" hx-get="/app/forderungen/liste"
-    hx-include="#liste-filter" hx-vals='{"page": {{ page + 1 }}, "limit": {{ limit }}}' hx-push-url="false">
+    hx-include="#liste-filter" hx-vals='{"page": {{ next_page }}, "limit": {{ limit }}}' hx-push-url="false">
   <td colspan="11">Weitere Forderungen werden geladen …</td>
 </tr>
 {% endif %}

+ 1 - 1
templates/forderungen/details/details.html

@@ -4,7 +4,7 @@
 {% set row = forderungen_details[0] %}
 <section class="gc-case-context" aria-label="Aktueller Beleg">
   <div class="gc-context-heading">
-    <a class="btn btn-link gc-back-link" href="{{ request.headers.referer or '/app/forderungen/liste' }}">← Zurück</a>
+    <a class="btn btn-link gc-back-link" href="{{ return_url }}" hx-boost="false" data-gc-return-url="{{ return_url }}">← Zurück</a>
     <h1>{{ row.Beleg_Text }}</h1>
     <p>{{ row.Kunde_Name }} <span>· {{ row.Kunde_Nr }}</span></p>
   </div>

+ 3 - 2
templates/forderungen/details/details_formular.html

@@ -3,6 +3,7 @@
 <form class="row g-3 gc-workflow-form" id="formular">
   <input type="hidden" name="_csrf" value="{{ request.state.principal.csrf }}" />
   <input type="hidden" name="source" value="details" />
+  <input type="hidden" name="return_to" value="{{ return_url }}" />
   <div class="col-12">
     <div class="form-check">
       <input class="form-check-input" type="checkbox" name="Versicherung" id="Versicherung" data-gc-collapse aria-controls="VersicherungCollapse" aria-expanded="{{ row.Versicherung|truefalse }}" {{
@@ -203,8 +204,8 @@
 
   <div class="col-12 gc-form-actions">
     <button type="button" class="btn btn-primary" hx-post="" hx-trigger="click" hx-swap="outerHTML" hx-target="#formular" hx-push-url="false">Speichern</button>
-    <button type="button" class="btn btn-outline-secondary" hx-post="" hx-trigger="click" hx-swap="innerHTML" hx-target="body" hx-push-url="true" hx-vals='{"redirect": "{{ request.headers.referer or '/app/forderungen/liste' }}"}'">Speichern &amp; Zurück</button>
-    <button type="button" class="btn btn-link" hx-get="{{ request.headers.referer or '/app/forderungen/liste' }}" hx-trigger="click" hx-swap="innerHTML" hx-target="body" hx-push-url="true">Zurück</button>
+    <button type="button" class="btn btn-outline-secondary" hx-post="" hx-trigger="click" hx-swap="innerHTML" hx-target="body" hx-push-url="true" hx-vals='{"redirect": "list"}'">Speichern &amp; Zurück</button>
+    <a class="btn btn-link" href="{{ return_url }}" hx-boost="false">Zurück</a>
   </div>
 
 

+ 1 - 1
templates/forderungen/details/notice.html

@@ -17,6 +17,6 @@
   {% else %}
   <p>Eintrag nicht gefunden.</p>
   {% endif %}
-  <a class="btn btn-primary" href="/app/forderungen/liste">Zurück zur Liste</a>
+  <a class="btn btn-primary" hx-boost="false" data-gc-return-url="{{ return_url }}" href="{{ return_url|default('/app/forderungen/liste') }}">Zurück zur Liste</a>
 </section>
 {% endblock %}

+ 5 - 2
templates/forderungen/liste/liste_zeile.html

@@ -1,6 +1,9 @@
 {% set comments_id = 'row-comments-' ~ (row.Client_DB|string|urlencode) ~ '-' ~ (row.Beleg_Nr|string|urlencode) %}
 {% set has_comments = row.Kommentar_Fibu or row.Kommentar_Abteilung or row.Antrag_Nr %}
-<tr class="gc-invoice-row">
+{% set primary_key = row.Client_DB|string ~ '_' ~ row.Beleg_Nr|string %}
+{% set origin = list_url|default('/app/forderungen/liste') %}
+{% set row_return_url = origin ~ ('&' if '?' in origin else '?') ~ 'focus=' ~ (primary_key|urlencode) %}
+<tr class="gc-invoice-row" data-primary-key="{{ primary_key }}" tabindex="-1">
   <td>
     <div class="gc-title">{{ row.Standort_Name }}</div>
     <div class="gc-subtitle">{{ row.Abteilung }}</div>
@@ -77,7 +80,7 @@
   </td>
 
   <td>
-    <a href="/app/forderungen/details/{{ row.Client_DB }}_{{ row.Beleg_Nr }}"
+    <a href="/app/forderungen/details/{{ primary_key|urlencode }}?return_to={{ row_return_url|urlencode }}" data-gc-detail-link data-return-url="{{ row_return_url }}"
       class="btn gc-action-btn" aria-label="Details zu Beleg {{ row.Beleg_Nr }} öffnen" title="Details öffnen">
       <i class="icon cil-magnifying-glass" aria-hidden="true"></i>
     </a>

+ 3 - 1
tests/test_forderung_history.py

@@ -8,6 +8,7 @@ import unittest
 from datetime import date, datetime
 from html.parser import HTMLParser
 from unittest.mock import patch
+from urllib.parse import parse_qs, urlsplit
 
 from fastapi import FastAPI
 from fastapi.testclient import TestClient
@@ -305,7 +306,8 @@ class HistoryTests(unittest.TestCase):
         self.assertEqual(len(selected), 2)
         self.assertTrue(all(a['hx-get'].endswith('scope=invoice') for a in selected))
         form = next(a for t, a in tags if a.get('id') == 'comment-form')
-        self.assertEqual(form['hx-post'], '/app/forderungen/details/1_R1')
+        self.assertEqual(urlsplit(form['hx-post']).path, '/app/forderungen/details/1_R1')
+        self.assertEqual(parse_qs(urlsplit(form['hx-post']).query)['return_to'], ['/app/forderungen/liste?focus=1_R1'])
         self.assertEqual(form['hx-target'], '#comments-history')
         self.assertIn('Keine Kommentare', response.text)
         self.assertIn('Keine Buchungsbelege', response.text)

+ 36 - 0
tests/test_forderung_list.py

@@ -140,6 +140,42 @@ class ForderungListTests(unittest.TestCase):
         self.assertNotIn('Abteilung Kommentar', response.text)
         self.assertEqual(response.text.count('data-gc-comments'), 1)
 
+    def test_return_focus_loads_through_target_and_continues_at_next_block(self):
+        self.db.rows = [invoice(n) for n in range(305)]
+        response = self.client.get('/app/forderungen/liste?Filiale=10&focus=1_R220')
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(response.text.count('class="gc-invoice-row"'), 300)
+        self.assertIn('data-primary-key="1_R220"', response.text)
+        self.assertIn('"page": 3', response.text)
+        self.assertIn('id="list-count">305', response.text)
+        self.assertEqual(response.headers['cache-control'], 'no-store')
+        sql, parameters = self.db.calls[-1]
+        self.assertNotIn('focus', parameters)
+        self.assertNotIn('focus', sql.lower())
+
+    def test_focus_is_found_at_new_position_and_within_exact_tenant(self):
+        self.db.rows = [invoice(220, Client_DB='2')] + [invoice(n) for n in range(150)] + [invoice(220)]
+        response = self.client.get('/app/forderungen/liste?Filiale=10&focus=1_R220')
+        self.assertEqual(response.text.count('class="gc-invoice-row"'), 152)
+        self.assertNotIn('gc-return-status', response.text)
+        self.assertIn('data-focus="1_R220"', response.text)
+
+    def test_missing_focus_preserves_filters_and_explains_missing_row(self):
+        response = self.client.get('/app/forderungen/liste?Filiale=10&focus=1_R404')
+        self.assertIn('nicht mehr enthalten', response.text)
+        self.assertIn('<option value="10" selected>10</option>', response.text)
+        self.assertIn('Keine Forderungen', response.text)
+
+    def test_detail_links_keep_filters_including_on_loaded_fragments(self):
+        from urllib.parse import parse_qs, urlsplit
+        self.db.rows = [invoice(n) for n in range(103)]
+        for url, key in [('/app/forderungen/liste?Filiale=10&Kunde=Muster', '1_R0'),
+                         ('/app/forderungen/liste?page=1&Filiale=10&Kunde=Muster', '1_R100')]:
+            response = self.client.get(url)
+            link = next(a for t, a in Tags(response.text).tags if 'data-gc-detail-link' in a)
+            return_to = parse_qs(urlsplit(link['href']).query)['return_to'][0]
+            self.assertEqual(parse_qs(urlsplit(return_to).query), {'Filiale': ['10'], 'Kunde': ['Muster'], 'focus': [key]})
+
 
 if __name__ == '__main__':
     unittest.main()

+ 1 - 1
tests/test_forderung_notice.py

@@ -50,7 +50,7 @@ class ForderungNoticeTests(unittest.TestCase):
 
     def assert_notice(self, response):
         self.assertEqual(response.status_code, 200)
-        self.assertIn('href="/app/forderungen/liste">Zurück zur Liste', response.text)
+        self.assertIn('href="/app/forderungen/liste?focus=1_WGG24501320">Zurück zur Liste', response.text)
         self.assertNotIn('id="formular"', response.text)
         self.assertNotIn('name="Kommentar"', response.text)
         self.detail_context.assert_not_called()

+ 164 - 0
tests/test_navigation.py

@@ -0,0 +1,164 @@
+import unittest
+from unittest.mock import patch, MagicMock
+from urllib.parse import parse_qs, urlencode, urlsplit
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from types import SimpleNamespace
+from datetime import date
+
+from app.db import get_session
+from app.routes import router
+
+from app.config import settings
+from app.ldap import DirectoryUser
+from app.main import app
+from app.navigation import LIST_PATH, list_return_url, normalize_page_url
+from app.permissions import Entitlement
+
+
+class NavigationUrlTests(unittest.TestCase):
+    def test_return_url_preserves_filters_and_replaces_transport_and_focus(self):
+        value = LIST_PATH + '?Filiale=10&Kunde=A%26B&page=3&limit=100&scope=debtor&focus=2_OTHER'
+        result = list_return_url(value, '1_R1')
+        self.assertEqual(parse_qs(urlsplit(result).query), {'Filiale': ['10'], 'Kunde': ['A&B'], 'focus': ['1_R1']})
+
+    def test_invalid_return_destinations_fall_back_to_filtered_page_type(self):
+        for value in ['https://evil.test/', '//evil.test', '/\\evil', '/%2f%2fevil', '/select', '/app/forderungen/liste\n']:
+            with self.subTest(value=value):
+                self.assertEqual(list_return_url(value, '1_R1'), LIST_PATH + '?focus=1_R1')
+
+    def test_fragment_recovery_uses_only_matching_invoice_context(self):
+        return_to = LIST_PATH + '?Filiale=10&focus=1_R1'
+        current = 'https://external-proxy.test/app/forderungen/details/1_R1?' + urlencode({'return_to': return_to})
+        for fragment in ['kommentare', 'buchungen']:
+            result = normalize_page_url('/app/forderungen/details/1_R1/' + fragment + '?scope=debtor', current_url=current)
+            self.assertEqual(result, '/app/forderungen/details/1_R1?' + urlencode({'return_to': return_to}))
+        self.assertEqual(normalize_page_url('/app/forderungen/details/2_R1/kommentare', current_url=current),
+                         '/app/forderungen/details/2_R1')
+
+    def test_external_current_url_never_becomes_redirect_origin(self):
+        result = normalize_page_url('/app/forderungen/details/1_R1/buchungen',
+                                    current_url='https://evil.test/app/forderungen/details/1_R1?return_to=https://evil.test')
+        self.assertTrue(result.startswith('/app/forderungen/details/1_R1?'))
+        self.assertNotIn('evil', result)
+
+
+class LoginRecoveryTests(unittest.TestCase):
+    def setUp(self):
+        config = patch.multiple(settings, DEBUG_AUTH=False, TRUSTED_PROXY_IPS=[], COOKIE_SECURE=False)
+        config.start()
+        self.addCleanup(config.stop)
+        session = patch('app.auth.SessionLocal', return_value=MagicMock())
+        session.start()
+        self.addCleanup(session.stop)
+        self.client = TestClient(app)
+        self.addCleanup(self.client.close)
+
+    def login_target(self, response):
+        self.assertEqual(response.status_code, 200)
+        login = response.headers['HX-Redirect']
+        self.assertTrue(login.startswith('/login?next='))
+        return parse_qs(urlsplit(login).query)['next'][0]
+
+    def test_expired_list_paging_resumes_full_filtered_page(self):
+        response = self.client.get(LIST_PATH + '?page=3&limit=100&Filiale=10', headers={
+            'HX-Request': 'true', 'HX-Current-URL': 'http://testserver' + LIST_PATH + '?Filiale=10&focus=1_R120',
+        }, follow_redirects=False)
+        self.assertEqual(self.login_target(response), LIST_PATH + '?Filiale=10&focus=1_R120')
+
+    def test_fragment_and_save_expiry_resume_detail_without_replaying_post(self):
+        return_to = LIST_PATH + '?Filiale=10&Kunde=Muster&focus=1_R1'
+        current = 'http://testserver/app/forderungen/details/1_R1?' + urlencode({'return_to': return_to})
+        headers = {'HX-Request': 'true', 'HX-Current-URL': current}
+        for suffix in ['/kommentare?scope=debtor', '/buchungen?scope=open', '']:
+            with self.subTest(suffix=suffix):
+                if suffix:
+                    response = self.client.get('/app/forderungen/details/1_R1' + suffix, headers=headers)
+                else:
+                    response = self.client.post('/app/forderungen/details/1_R1', headers=headers,
+                                                data={'source': 'details', 'return_to': return_to})
+                self.assertEqual(self.login_target(response), current.removeprefix('http://testserver'))
+
+    def test_login_post_normalizes_fragment_next_to_full_get(self):
+        self.client.get('/login')
+        csrf = self.client.cookies[settings.LOGIN_CSRF_COOKIE_NAME]
+        user = DirectoryUser('tester', 'CN=tester', 'Tester', '')
+        rights = (Entitlement('1', '10', 'SC', 'Mitarbeiter', 100),)
+        with patch('app.routes.ldap_authenticate', return_value=user), patch('app.routes.load_entitlements', return_value=rights):
+            response = self.client.post('/login', data={
+                'username': 'tester', 'password': 'test', '_csrf': csrf,
+                'next': '/app/forderungen/details/1_R1/kommentare?scope=debtor',
+            }, follow_redirects=False)
+        self.assertEqual(response.status_code, 303)
+        self.assertEqual(response.headers['location'], '/app/forderungen/details/1_R1')
+
+    def test_native_page_request_uses_full_page_redirect(self):
+        response = self.client.get(LIST_PATH + '?Filiale=10', follow_redirects=False)
+        self.assertEqual(response.status_code, 303)
+        self.assertEqual(parse_qs(urlsplit(response.headers['location']).query)['next'], [LIST_PATH + '?Filiale=10'])
+
+
+class DetailReturnTests(unittest.TestCase):
+    def setUp(self):
+        self.db = MagicMock()
+        self.db.execute.return_value.first.return_value = (1,)
+        application = FastAPI()
+        application.include_router(router)
+        application.dependency_overrides[get_session] = lambda: self.db
+
+        @application.middleware('http')
+        async def identity(request, call_next):
+            request.state.principal = SimpleNamespace(username='tester', name='Tester', role='Mitarbeiter', csrf='csrf')
+            return await call_next(request)
+
+        self.client = TestClient(application, raise_server_exceptions=False)
+        self.addCleanup(self.client.close)
+        self.row = dict(Client_DB='1', Beleg_Nr='R1', Beleg_Text='Rechnung R1', Beleg_offen=10,
+                        Kunde_offen_gesamt=20, Beleg_Datum=date(2026, 10, 1),
+                        Fahrzeug_Erstzulassung=None, Fahrzeug_Kaufdatum=None, Wiedervorlage=date(2026, 11, 1),
+                        Mwst_Betrag=0, Mwst_Betrag_berechnet=1.9)
+        context = dict(forderungen_details=[self.row], forderungen_kommentare=[], forderungen_buchungen=[],
+                       auftraege_positionen=[], versicherungen=[], files=[], detail_url='/app/forderungen/details/1_R1',
+                       kommentare_scope='invoice', buchungen_scope='invoice', vehicle_missing=False, summary=False)
+        fixture = patch('app.routes.get_template_context', side_effect=lambda *args: dict(context))
+        fixture.start()
+        self.addCleanup(fixture.stop)
+        self.return_url = LIST_PATH + '?Filiale=10&Kunde=Muster&focus=1_R1'
+
+    def test_detail_and_saved_form_keep_explicit_return_context(self):
+        response = self.client.get('/app/forderungen/details/1_R1?' + urlencode({'return_to': self.return_url}))
+        self.assertEqual(response.status_code, 200)
+        self.assertIn('Filiale=10&amp;Kunde=Muster&amp;focus=1_R1', response.text)
+        response = self.client.post('/app/forderungen/details/1_R1', data={
+            'source': 'details', 'return_to': self.return_url,
+        }, headers={'HX-Request': 'true', 'Referer': 'http://testserver/app/forderungen/details/1_R1'})
+        self.assertEqual(response.status_code, 200)
+        self.assertIn('name="return_to" value="/app/forderungen/liste?Filiale=10&amp;Kunde=Muster&amp;focus=1_R1"', response.text)
+        self.assertEqual(self.db.commit.call_count, 1)
+
+    def test_save_and_back_redirects_after_commit_to_full_list(self):
+        response = self.client.post('/app/forderungen/details/1_R1', data={
+            'source': 'details', 'return_to': self.return_url, 'redirect': 'list',
+        }, headers={'HX-Request': 'true'})
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(response.headers['HX-Redirect'], self.return_url)
+        self.db.commit.assert_called_once()
+        native = self.client.post('/app/forderungen/details/1_R1', data={
+            'source': 'details', 'return_to': self.return_url, 'redirect': 'list',
+        }, follow_redirects=False)
+        self.assertEqual(native.status_code, 303)
+        self.assertEqual(native.headers['location'], self.return_url)
+
+    def test_failed_save_does_not_return_and_external_target_is_ignored(self):
+        self.db.commit.side_effect = RuntimeError('test database unavailable')
+        response = self.client.post('/app/forderungen/details/1_R1', data={
+            'source': 'details', 'return_to': self.return_url, 'redirect': 'list',
+        }, headers={'HX-Request': 'true'})
+        self.assertEqual(response.status_code, 500)
+        self.assertNotIn('HX-Redirect', response.headers)
+        self.db.commit.side_effect = None
+        response = self.client.post('/app/forderungen/details/1_R1', data={
+            'source': 'details', 'redirect': 'https://evil.test',
+        }, headers={'HX-Request': 'true'})
+        self.assertEqual(response.headers['HX-Redirect'], LIST_PATH + '?focus=1_R1')