From e1d28f971d7acae66ef3fce46af357c9449eae54 Mon Sep 17 00:00:00 2001 From: Daniel Santillan Date: Wed, 23 Sep 2026 19:57:43 -0400 Subject: [PATCH] =?UTF-8?q?El=20registro=20de=20actividad=20abre=20plegado?= =?UTF-8?q?=20en=20los=20diez=20m=C3=A1s=20nuevos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Muéstrame los últimos 10 y que diga mostrar más, para que no se vea todo eso para abajo." Exacto: con 25 eventos el registro llenaba la pantalla y empujaba el resto del panel fuera de vista, y con un día movido son cientos. El encabezado ya decía cuántos hay ("25 events, kept for 90 days"); el cuerpo ahora empieza por los diez más nuevos y un botón **Show more** revela diez más por vez. Tres detalles que lo hacen correcto en vez de sólo corto: · **Lo que ya está cargado se revela antes de pedir nada.** El botón revela de la lista que tiene y sólo va al servidor cuando no le queda nada por mostrar — y entonces pide la página siguiente con `before`, que ya sabía hacer. Sin esto, cada clic sería un viaje de red para datos que ya estaban en memoria. · **Al lado del botón dice "10 of 25"**, así que nunca queda la duda de cuánto falta; el número sale del `total` del servidor, no del largo de lo cargado. · **El botón desaparece cuando no queda nada**, en vez de quedarse invitando a un clic que no hace nada. Y al recargar (el ↻ del encabezado) vuelve a plegarse, que es el punto de plegarlo. De paso, `load` ya no asume que la respuesta traiga `events`: una respuesta sin eventos es una respuesta sin eventos, no un crash — y un crash acá se lleva la tarjeta entera del panel. Tests: 4 en `Admin.test.jsx` (abre en diez y revela hasta el final; pide la página siguiente cuando se le acaba lo cargado, y no antes; log vacío sin botón). Mutation-check de las dos mitades: sin el recorte se renderizan todos, y con la página en 50 fallan los dos de plegado. --- frontend/src/views/Admin.jsx | 35 ++++++++++++---- frontend/src/views/Admin.test.jsx | 69 ++++++++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 8 deletions(-) diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx index 22ec22a..016c940 100644 --- a/frontend/src/views/Admin.jsx +++ b/frontend/src/views/Admin.jsx @@ -157,19 +157,38 @@ function InvitesCard({ invites, reload, inviteOnly }) { // Who signed in, who tried and failed, what an admin changed. A card rather than its own route: // the dashboard is deliberately one page of cards, and the 95 % use of this is a glance at the // last twenty events. Paging follows Library.jsx's house style — "Show more", not page numbers. +/* How many events the card shows before somebody asks for more. + * + * The log is history and history is long: twenty-five rows is a wall of text that pushes the rest of + * the dashboard off the screen, and a cleared log is a full one again the next day. The count in the + * lead line says how much there is — the newest ten are shown, and one button reveals the rest, ten + * at a time, fetching from the server once everything already loaded is on screen. */ +const AUDIT_PAGE = 10 + function AuditCard({ tick }) { const toast = useUI(s => s.toast) const [meta, setMeta] = useState(null) // last response minus the rows: total, retention, … const [rows, setRows] = useState([]) const [cat, setCat] = useState('') + const [shown, setShown] = useState(AUDIT_PAGE) const load = (c, before) => api('/api/admin/audit?limit=50&cat=' + c + (before ? '&before=' + before : '')) - .then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events) : r.events)) }) + // `|| []` because a response without events is a response with no events, not a crash: an + // admin card that throws takes the whole dashboard with it. + .then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events || []) : (r.events || []))) }) .catch(e => toast(e.message)) - const pick = c => { setCat(c); setRows([]); setMeta(null); load(c) } + const pick = c => { setCat(c); setRows([]); setMeta(null); setShown(AUDIT_PAGE); load(c) } // Reloads on mount and whenever the header's ↻ bumps the tick. Deliberately not on the 15s - // poll that drives "training now": this is history, not presence. - useEffect(() => { load(cat) }, [tick]) + // poll that drives "training now": this is history, not presence. A reload starts folded again, + // which is the point of folding it. + useEffect(() => { setShown(AUDIT_PAGE); load(cat) }, [tick]) + + const hidden = rows.length - shown + const more = () => { + setShown(n => n + AUDIT_PAGE) + // Everything already fetched is on screen: the next ten come from the server. + if (hidden <= 0 && meta?.nextBefore) load(cat, meta.nextBefore) + } const clear = () => confirmSheet({ title: 'Clear the activity log?', @@ -194,7 +213,7 @@ function AuditCard({ tick }) { {[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) => )} - {rows.map(e => { + {rows.slice(0, shown).map(e => { const line = auditLine(e) return
@@ -208,8 +227,10 @@ function AuditCard({ tick }) {
})} {meta && !rows.length &&
Nothing logged yet.
} - {meta?.nextBefore &&
-
} + {(hidden > 0 || meta?.nextBefore) &&
+ + {meta && {fmtNum(Math.min(shown, rows.length))} of {fmtNum(meta.total)}} +
}
} diff --git a/frontend/src/views/Admin.test.jsx b/frontend/src/views/Admin.test.jsx index d3cdba6..bfdaab1 100644 --- a/frontend/src/views/Admin.test.jsx +++ b/frontend/src/views/Admin.test.jsx @@ -9,9 +9,10 @@ import Admin from './Admin.jsx' globalThis.IS_REACT_ACT_ENVIRONMENT = true -const mocks = vi.hoisted(() => ({ answers: {}, sheets: [] })) +const mocks = vi.hoisted(() => ({ answers: {}, sheets: [], calls: [] })) vi.mock('../lib/api.js', () => ({ api: path => { + mocks.calls.push(path) const key = path.split('?')[0] return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found')) } @@ -48,6 +49,7 @@ const good = { id: 'w1', name: 'Push day', d: '2026-09-10', start: 1000, end: 61 beforeEach(() => { document.body.innerHTML = '' mocks.sheets.length = 0 + mocks.calls.length = 0 mocks.answers = { '/api/admin/users': { users: [{ id: 'u1', name: 'Mallory', workouts: 2, lastSync: null, disabled: false }], invite_only: false }, '/api/admin/invites': { invites: [] }, @@ -63,6 +65,71 @@ beforeEach(() => { }) afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) }) +/* The activity log is history, and history grows: one line per sign-in, per failed attempt, per + admin action. Reported as a wall of twenty-five rows pushing the rest of the dashboard off the + screen. It opens folded to the newest ten with the total in the lead line, and one button reveals + the rest — from what is already loaded first, and from the server once that runs out. */ +describe('the activity log', () => { + const withLog = (n, extra = {}) => { + mocks.answers['/api/admin/audit'] = { + events: Array.from({ length: n }, (_, i) => ({ id: n - i, ts: Date.now() - i * 60000, ev: 'auth.login.ok', uid: 'u1', name: 'Daniel', ok: true })), + total: n, nextBefore: null, enabled: true, ip_mode: 'off', retention: { days: 90, max: 5000 }, now: Date.now(), ...extra + } + } + const auditCard = page => [...page.querySelectorAll('.card')].find(c => c.textContent.includes('Activity log')) + const auditRows = card => [...card.querySelectorAll('.row.between')].filter(r => r.querySelector('.small.muted')) + const showMore = card => [...card.querySelectorAll('button')].find(b => b.textContent.trim() === 'Show more') + + it('opens with the newest ten and reveals the rest on demand', async () => { + withLog(25) + const page = render() + await settle() + const card = auditCard(page) + expect(auditRows(card).length).toBe(10); + expect(card.textContent).toContain('25 events') + expect(card.textContent).toContain('10 of 25') + + act(() => showMore(card).click()) + await settle() + expect(auditRows(card).length).toBe(20) + expect(card.textContent).toContain('20 of 25') + + act(() => showMore(card).click()) + await settle() + expect(auditRows(card).length).toBe(25) + // Everything is on screen and nothing is left on the server: the button goes away rather than + // sitting there inviting a click that does nothing. + expect(showMore(card)).toBeFalsy() + }) + + it('asks the server for the next page once what it has is shown', async () => { + // A page of fifty with more behind it: revealing past the fifty asks for the next page rather + // than sitting on a button that does nothing. + withLog(50, { total: 80, nextBefore: 3 }) + const page = render() + await settle() + const card = auditCard(page) + // Four clicks reveal the fifty that were already loaded — and none of them asks the server. + for (let i = 0; i < 4; i++) { act(() => showMore(card).click()); await settle() } + expect(auditRows(card).length).toBe(50) + expect(mocks.calls.some(c => c.includes('before=3'))).toBe(false, 'a page already here is not re-fetched') + expect(showMore(card)).toBeTruthy() + // The fifth has nothing left to reveal, so it goes and gets the next page. + act(() => showMore(card).click()) + await settle() + expect(mocks.calls.some(c => c.includes('before=3'))).toBe(true, 'and then it fetches'); + }) + + it('says nothing to show on an empty log, and no button', async () => { + withLog(0) + const page = render() + await settle() + const card = auditCard(page) + expect(card.textContent).toContain('Nothing logged yet.') + expect(showMore(card)).toBeFalsy() + }) +}) + describe('Admin user drill-down', () => { it('opens a profile with malformed workout entries and still offers "Disable account"', async () => { const page = render()