feat(audit): every row keeps its date; dividers for Today, Yesterday, Last 7 days, Older (#5214)

The operator found "Today 08:03" in place of a date odd on the audit log,
and asked for the recency groups as dividers instead. |when now always
writes the date ("Thu 8 Oct 08:03"); mark_day_groups gives each entry its
group in the reader's zone, and a divider row opens each group. A scrolled
page carries the group the last one ended in, so it is not opened twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 08:22:03 -04:00
co-authored by Claude Opus 5.5
parent 31e93e96cf
commit 7a444da871
7 changed files with 100 additions and 26 deletions
+6 -3
View File
@@ -1,10 +1,11 @@
from __future__ import annotations
import json
from quart import Blueprint, render_template, request, current_app
from quart import Blueprint, render_template, request, current_app, session
from sqlalchemy import select
from steward.ansible.inventory_gen import scope_labels
from steward.audit.service import AREAS, action_text, detail_facts, entity_labels
from steward.audit.service import AREAS, action_text, detail_facts, entity_labels, mark_day_groups
from steward.auth.middleware import require_role
from steward.core import formatting as fmt
from steward.core.paging import keyset, next_page
from steward.models.audit import AuditEvent
from steward.models.users import UserRole
@@ -46,7 +47,9 @@ async def list_events():
item["action"] = action_text(e.action)
item["facts"] = detail_facts(item["detail"], scopes)
ctx = {"events": parsed, "after": after, "action_filter": action_filter, "areas": AREAS}
last_group = mark_day_groups(parsed, fmt.zone(session.get("tz")), request.args.get("group", ""))
ctx = {"events": parsed, "after": after, "action_filter": action_filter, "areas": AREAS,
"last_group": last_group}
if request.args.get("before"):
return await render_template("audit/_rows.html", **ctx)
return await render_template("audit/list.html", **ctx)
+13
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
from sqlalchemy import select
from steward.ansible.inventory_gen import run_title, scope_labels
from steward.core.formatting import day_group
from steward.models.alerts import AlertRule, MaintenanceWindow
from steward.models.ansible import AnsibleRun
from steward.models.ansible_inventory import AnsibleGroup, AnsibleTarget
@@ -207,3 +208,15 @@ def detail_facts(detail: dict, scopes: dict[str, str]) -> list[dict]:
text = _plain(value)
facts.append({"label": label, "text": text, "url": url})
return facts
def mark_day_groups(items: list[dict], tz, group: str = "", now=None) -> str:
"""Give each newest-first entry its recency group (formatting.day_group,
in the reader's zone) and whether it opens one, so the page draws a
divider there. `group` is the one the previous page ended in: a group
split across pages is opened once. Returns the group this page ends in."""
for item in items:
item["group"] = day_group(item["event"].timestamp, tz, now)
item["opens_group"] = item["group"] != group
group = item["group"]
return group
+23 -12
View File
@@ -9,7 +9,7 @@ here. A moment is written in the reader's own zone, on a 24-hour clock
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone, tzinfo
from datetime import datetime, timezone, tzinfo
from functools import lru_cache
from typing import Any
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
@@ -120,29 +120,40 @@ def ago(when: datetime | None, now: datetime | None = None, tz: tzinfo | None =
def when(moment: datetime | None, tz: tzinfo | None = None, now: datetime | None = None) -> Markup:
"""The exact moment in the reader's zone on a 24-hour clock, as short as
it can be read: 'Today 06:58', 'Yesterday 23:41', 'Tomorrow 02:00',
'Tue 6 Oct 14:12' this year, '6 Oct 2025 14:12' before it."""
"""The exact moment in the reader's zone on a 24-hour clock, always with
its date: 'Thu 8 Oct 06:58' this year, '6 Oct 2025 14:12' before it. A
list that groups by recency says Today or Yesterday in a divider
(day_group), never in place of the date (#5214)."""
if moment is None:
return Markup(NONE)
tz = tz or timezone.utc
moment = _utc(moment)
local = moment.astimezone(tz)
today = (now or datetime.now(timezone.utc)).astimezone(tz).date()
this_year = (now or datetime.now(timezone.utc)).astimezone(tz).year
day, hm = local.date(), f"{local:%H:%M}"
if day == today:
text = f"Today {hm}"
elif day == today - timedelta(days=1):
text = f"Yesterday {hm}"
elif day == today + timedelta(days=1):
text = f"Tomorrow {hm}"
elif day.year == today.year:
if day.year == this_year:
text = f"{local:%a} {day.day} {local:%b} {hm}"
else:
text = f"{day.day} {local:%b} {day.year} {hm}"
return _time(moment, local, text)
DAY_GROUPS = ("Today", "Yesterday", "Last 7 days", "Older")
def day_group(moment: datetime, tz: tzinfo | None = None, now: datetime | None = None) -> str:
"""Which of DAY_GROUPS a past moment falls in, by calendar day in the
reader's zone: the dividers of a newest-first log."""
tz = tz or timezone.utc
day = _utc(moment).astimezone(tz).date()
back = ((now or datetime.now(timezone.utc)).astimezone(tz).date() - day).days
if back <= 0:
return DAY_GROUPS[0]
if back == 1:
return DAY_GROUPS[1]
return DAY_GROUPS[2] if back < 7 else DAY_GROUPS[3]
def status_class(value: Any, kind: str, thresholds: dict) -> str:
"""Grade a reading against Settings → Thresholds (to_thresholds_cfg):
'ok', 'warn' or 'crit', or 'unknown' when there is no reading.
+3
View File
@@ -227,6 +227,9 @@ strong, b, th { font-weight: 500; }
.table td.nowrap { white-space: nowrap; }
/* An audit entry's details, one fact a line (milestone 490). */
.audit-facts { font-size: 0.8rem; color: var(--text-muted); }
/* A divider row naming the group the rows under it fall in (Today, Older). */
.table tr.table-divider th { padding: 1rem 1rem 0.4rem; background: var(--bg-card); border-bottom: 1px solid var(--border-mid); }
.table tbody tr.table-divider:hover th { background: var(--bg-card); }
.cell-note { font-size: 0.78rem; color: var(--text-muted); margin-top: 0.2rem; }
/* An alert episode's own transitions, folded under it (#5316). */
.episode-steps { margin-top: 0.3rem; font-size: 0.8rem; }
+5 -2
View File
@@ -1,8 +1,10 @@
{# audit/_rows.html — one page of the audit log's rows, then the sentinel that
loads the next page as the reader nears it (core.paging, pref 172). #}
loads the next page as the reader nears it (core.paging, pref 172). A
divider row opens each recency group: Today, Yesterday, Last 7 days, Older. #}
{% from "_macros.html" import scroll_more, scroll_end %}
{% for item in events %}
{% set e = item.event %}
{% if item.opens_group %}<tr class="table-divider"><th colspan="5" scope="rowgroup">{{ item.group }}</th></tr>{% endif %}
<tr>
<td class="nowrap">{{ e.timestamp|when }}</td>
<td class="nowrap">{{ e.username }}</td>
@@ -22,7 +24,8 @@
</tr>
{% endfor %}
{% if after %}
{{ scroll_more("/audit/?before=" ~ (after|urlencode) ~ (("&action=" ~ (action_filter|urlencode)) if action_filter else ""), cols=5) }}
{{ scroll_more("/audit/?before=" ~ (after|urlencode) ~ (("&action=" ~ (action_filter|urlencode)) if action_filter else "")
~ "&group=" ~ (last_group|urlencode), cols=5) }}
{% else %}
{{ scroll_end(cols=5) }}
{% endif %}