diff --git a/steward/audit/routes.py b/steward/audit/routes.py index e363345..3400aa5 100644 --- a/steward/audit/routes.py +++ b/steward/audit/routes.py @@ -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) diff --git a/steward/audit/service.py b/steward/audit/service.py index f647f4c..adde7b5 100644 --- a/steward/audit/service.py +++ b/steward/audit/service.py @@ -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 diff --git a/steward/core/formatting.py b/steward/core/formatting.py index aefa87b..7194b03 100644 --- a/steward/core/formatting.py +++ b/steward/core/formatting.py @@ -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. diff --git a/steward/static/steward.css b/steward/static/steward.css index c6cbc49..22fe2dd 100644 --- a/steward/static/steward.css +++ b/steward/static/steward.css @@ -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; } diff --git a/steward/templates/audit/_rows.html b/steward/templates/audit/_rows.html index 5ab9e07..12ea06a 100644 --- a/steward/templates/audit/_rows.html +++ b/steward/templates/audit/_rows.html @@ -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 %}{{ item.group }}{% endif %} {{ e.timestamp|when }} {{ e.username }} @@ -22,7 +24,8 @@ {% 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 %} diff --git a/tests/core/test_audit_page.py b/tests/core/test_audit_page.py index 1a99109..b5ef73f 100644 --- a/tests/core/test_audit_page.py +++ b/tests/core/test_audit_page.py @@ -49,11 +49,11 @@ async def test_the_page_names_and_links_the_entity(app): async def test_the_log_continues_itself_instead_of_a_load_more_link(app): events = [{"event": _ev("host", "h1", "host.renamed"), "detail": {}, "entity": None}] async with app.test_request_context("/audit/"): - more = await render_template("audit/list.html", events=events, + more = await render_template("audit/list.html", events=events, last_group="Today", after="2026-10-07T03:00:00+00:00|0190abc", action_filter="host.") last = await render_template("audit/_rows.html", events=events, after=None, action_filter="") assert ('data-scroll-more hx-get="/audit/?before=2026-10-07T03%3A00%3A00%2B00%3A00%7C0190abc' - '&action=host."') in more + '&action=host.&group=Today"') in more assert "Load more" not in more assert "data-scroll-more" not in last and "End of the list." in last @@ -107,3 +107,30 @@ async def test_each_entry_shows_its_exact_moment_in_the_readers_zone(app): assert '
was web-0
' in page table = page[page.index(''):] assert "style=" not in table + + +def test_dividers_open_each_day_group_once_even_across_pages(): + """#5214: the operator wants Today, Yesterday, the last week and older as + dividers, with every row's own date beside it.""" + from steward.audit.service import mark_day_groups + now = datetime(2026, 10, 8, 18, 0, tzinfo=timezone.utc) + at = lambda d, h=12: NS(timestamp=datetime(2026, 10, d, h, 0, tzinfo=timezone.utc)) + page1 = [{"event": at(8)}, {"event": at(8, 9)}, {"event": at(7)}, {"event": at(5)}] + assert mark_day_groups(page1, timezone.utc, "", now) == "Last 7 days" + assert [(i["group"], i["opens_group"]) for i in page1] == [ + ("Today", True), ("Today", False), ("Yesterday", True), ("Last 7 days", True)] + # The next page carries the group the last ended in, so it doesn't reopen it. + page2 = [{"event": at(3)}, {"event": at(1)}] + assert mark_day_groups(page2, timezone.utc, "Last 7 days", now) == "Older" + assert [(i["group"], i["opens_group"]) for i in page2] == [("Last 7 days", False), ("Older", True)] + + +async def test_a_divider_row_heads_each_group(app): + events = [{"event": _ev("host", "h1", "host.renamed"), "detail": {}, "entity": None, "facts": [], + "group": "Today", "opens_group": True}, + {"event": _ev("host", "h1", "host.renamed"), "detail": {}, "entity": None, "facts": [], + "group": "Today", "opens_group": False}] + async with app.test_request_context("/audit/"): + page = await render_template("audit/_rows.html", events=events, after=None, action_filter="") + assert page.count('') == 1 + assert "Today 1" not in page and ">Tue 6 Oct " in page # the row keeps its date diff --git a/tests/core/test_formatting.py b/tests/core/test_formatting.py index 295719a..f560de6 100644 --- a/tests/core/test_formatting.py +++ b/tests/core/test_formatting.py @@ -57,7 +57,8 @@ def test_ago_of_nothing_and_of_another_zone(): assert 'title="Tue 6 Oct 2026 18:00:00 UTC"' in str(f.ago(NOW.astimezone(est), now=NOW)) -# Milestone 490: a moment in the reader's own zone, on a 24-hour clock. +# Milestone 490: a moment in the reader's own zone, on a 24-hour clock, always +# with its date: "Today" and "Yesterday" are dividers, never the time (#5214). NY = f.zone("America/New_York") @@ -67,14 +68,14 @@ def test_ago_hovers_the_moment_in_the_readers_zone(): @pytest.mark.parametrize("moment, text, title", [ - (NOW - timedelta(hours=1), "Today 13:00", "Tue 6 Oct 2026 13:00:00 EDT"), + (NOW - timedelta(hours=1), "Tue 6 Oct 13:00", "Tue 6 Oct 2026 13:00:00 EDT"), # 03:30 UTC on the 6th is 23:30 on the 5th in New York: the zone moves the day. - (datetime(2026, 10, 6, 3, 30, tzinfo=timezone.utc), "Yesterday 23:30", "Mon 5 Oct 2026 23:30:00 EDT"), - (datetime(2026, 10, 7, 6, 0, tzinfo=timezone.utc), "Tomorrow 02:00", "Wed 7 Oct 2026 02:00:00 EDT"), + (datetime(2026, 10, 6, 3, 30, tzinfo=timezone.utc), "Mon 5 Oct 23:30", "Mon 5 Oct 2026 23:30:00 EDT"), + (datetime(2026, 10, 7, 6, 0, tzinfo=timezone.utc), "Wed 7 Oct 02:00", "Wed 7 Oct 2026 02:00:00 EDT"), (datetime(2026, 9, 30, 12, 0, tzinfo=timezone.utc), "Wed 30 Sep 08:00", "Wed 30 Sep 2026 08:00:00 EDT"), # Before this year the year shows; in winter the zone is EST, an hour further back. (datetime(2025, 12, 25, 12, 0, tzinfo=timezone.utc), "25 Dec 2025 07:00", "Thu 25 Dec 2025 07:00:00 EST"), - (datetime(2026, 10, 6, 21, 5), "Today 17:05", "Tue 6 Oct 2026 17:05:00 EDT"), # naive is UTC + (datetime(2026, 10, 6, 21, 5), "Tue 6 Oct 17:05", "Tue 6 Oct 2026 17:05:00 EDT"), # naive is UTC ]) def test_when_writes_the_exact_moment_in_the_readers_zone(moment, text, title): stamp = moment.replace(tzinfo=timezone.utc) if moment.tzinfo is None else moment @@ -83,11 +84,24 @@ def test_when_writes_the_exact_moment_in_the_readers_zone(moment, text, title): def test_when_is_a_24_hour_clock_and_utc_without_a_zone(): - assert ">Today 18:00<" in str(f.when(NOW, now=NOW)) - assert ">Today 23:59<" in str(f.when(NOW.replace(hour=23, minute=59), now=NOW)) + assert ">Tue 6 Oct 18:00<" in str(f.when(NOW, now=NOW)) + assert ">Tue 6 Oct 23:59<" in str(f.when(NOW.replace(hour=23, minute=59), now=NOW)) assert str(f.when(None)) == "—" +@pytest.mark.parametrize("moment, group", [ + (NOW - timedelta(hours=1), "Today"), + (datetime(2026, 10, 6, 3, 30, tzinfo=timezone.utc), "Yesterday"), # 23:30 on the 5th in New York + (datetime(2026, 10, 5, 3, 30, tzinfo=timezone.utc), "Last 7 days"), + (datetime(2026, 9, 30, 12, 0, tzinfo=timezone.utc), "Last 7 days"), # six days back + (datetime(2026, 9, 29, 12, 0, tzinfo=timezone.utc), "Older"), # seven + (datetime(2025, 12, 25, 12, 0, tzinfo=timezone.utc), "Older"), +]) +def test_day_group_counts_calendar_days_in_the_readers_zone(moment, group): + assert f.day_group(moment, NY, now=NOW) == group + assert group in f.DAY_GROUPS + + def test_zone_falls_back_to_utc_and_names_itself(): assert f.zone(None) is timezone.utc and f.zone("") is timezone.utc assert f.zone("Not/AZone") is timezone.utc and f.zone("../etc/passwd") is timezone.utc
Today