fix(admin): show when users were last active and keep the list current

The column showed the last sign-in, which a renewing cookie leaves weeks
behind for someone using TREK daily. It now shows the later of the sign-in
and the last request. Saving an edit no longer blanks the row's avatar,
activity and online dot, and the list refreshes every 30 seconds while open.
This commit is contained in:
Maurice
2026-10-14 10:45:39 +02:00
committed by Maurice
parent 4ceade9d8b
commit 3c8fa07f44
39 changed files with 267 additions and 37 deletions
@@ -102,6 +102,15 @@ describe('AdminUsersTab', () => {
expect(screen.getByText('A')).toBeInTheDocument();
});
it('FE-ADMUSR-006b: the column shows the last activity, not only the last sign-in', () => {
renderTab({
users: [buildAdminUser({ id: 5, username: 'busy', last_login: '2025-06-01T10:30:00.000Z', last_active: '2025-06-09T18:00:00.000Z' })],
});
expect(screen.getByRole('columnheader', { name: 'Last Active' })).toBeInTheDocument();
expect(screen.getByText(/9 Jun|Jun 9/)).toBeInTheDocument();
});
it('FE-ADMUSR-006: renders an em dash when the user never logged in', () => {
renderTab({ users: [buildAdminUser({ id: 4, username: 'never', last_login: null })] });
+4 -3
View File
@@ -9,7 +9,7 @@ import { EditorField, Segmented } from '../../components/shared/dialogParts'
import { SettingsCard, SettingRows, SettingsHint, StatusPill, SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON } from '../../components/Settings/settingsKit'
import type { TranslationFn } from '../../types'
import type { useAdmin } from './useAdmin'
import { inviteStatus } from './adminModel'
import { formatLastActive, inviteStatus } from './adminModel'
interface AdminUsersTabProps {
admin: ReturnType<typeof useAdmin>
@@ -73,7 +73,7 @@ export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps):
<th className={TH}>{t('admin.table.email')}</th>
<th className={TH}>{t('admin.table.role')}</th>
<th className={TH}>{t('admin.table.created')}</th>
<th className={TH}>{t('admin.table.lastLogin')}</th>
<th className={TH}>{t('admin.table.lastActive')}</th>
<th className={`${TH} text-end`}>{t('admin.table.actions')}</th>
</tr>
</thead>
@@ -114,7 +114,8 @@ export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps):
{new Date(u.created_at).toLocaleDateString(locale)}
</td>
<td className={`${TD} whitespace-nowrap font-geist tabular-nums text-content-muted`} style={fs(12)}>
{u.last_login ? new Date(u.last_login).toLocaleDateString(locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12 }) : '—'}
{/* Activity, not only sign-ins: a renewing cookie keeps people signed in for weeks. */}
{formatLastActive(u.last_active ?? u.last_login, locale, hour12)}
</td>
<td className={TD}>
<div className="flex items-center justify-end gap-1.5">
+39 -2
View File
@@ -1,7 +1,7 @@
// FE-ADMMODEL-001 to -005: the invite status both admin user views show.
// FE-ADMMODEL-001 to -005: the invite status both admin user views show; -010 to -012 the users list.
import { describe, expect, it } from 'vitest';
import { inviteStatus } from './adminModel';
import { formatLastActive, inviteStatus, mergeSavedUser, type AdminUser } from './adminModel';
const NOW = new Date('2026-10-09T12:00:00Z');
@@ -47,3 +47,40 @@ describe('inviteStatus', () => {
expect(inviteStatus({ expires_at: '2999-01-01T00:00:00Z', max_uses: 0, used_count: 0 }).isActive).toBe(true);
});
});
describe('formatLastActive', () => {
it('FE-ADMMODEL-010: a dash for never, the year only once it is not this one', () => {
expect(formatLastActive(null, 'en-GB', false, NOW)).toBe('—');
const thisYear = formatLastActive('2026-03-04T10:30:00Z', 'en-GB', false, NOW);
const lastYear = formatLastActive('2025-03-04T10:30:00Z', 'en-GB', false, NOW);
expect(thisYear).not.toContain('2026');
expect(lastYear).toContain('2025');
});
it('FE-ADMMODEL-011: follows the 12 and 24 hour setting', () => {
expect(formatLastActive('2026-03-04T15:30:00Z', 'en-US', true, NOW)).toMatch(/PM/i);
expect(formatLastActive('2026-03-04T15:30:00Z', 'en-US', false, NOW)).not.toMatch(/PM/i);
});
});
describe('mergeSavedUser', () => {
it('FE-ADMMODEL-012: takes the account fields from the reply and keeps the rest of the row', () => {
const row: AdminUser = {
id: 2,
username: 'old',
email: 'old@e.com',
role: 'user',
created_at: '2026-01-01T00:00:00Z',
last_login: '2026-10-01T08:00:00Z',
last_active: '2026-10-08T17:30:00Z',
online: true,
avatar_url: '/a.jpg',
};
expect(mergeSavedUser(row, { username: 'new', email: 'new@e.com', role: 'admin' })).toEqual({
...row,
username: 'new',
email: 'new@e.com',
role: 'admin',
});
});
});
+26
View File
@@ -7,11 +7,37 @@ export interface AdminUser {
role: 'admin' | 'user'
created_at: string
last_login?: string | null
/** The later of the last sign-in and the last request the account made. */
last_active?: string | null
online?: boolean
oidc_issuer?: string | null
avatar_url?: string | null
}
/**
* The row after an edit. The update answers with the account fields only, so
* what the list derives (avatar, last activity, online) stays from the row; a
* reply that replaced the whole row showed the user as never signed in.
*/
export function mergeSavedUser(row: AdminUser, saved: Pick<AdminUser, 'username' | 'email' | 'role'>): AdminUser {
return { ...row, username: saved.username, email: saved.email, role: saved.role }
}
/** When a user was last active, with the year once it is not this one. */
export function formatLastActive(iso: string | null | undefined, locale: string, hour12: boolean, now = new Date()): string {
if (!iso) return '—'
const at = new Date(iso)
const sameYear = at.getFullYear() === now.getFullYear()
return at.toLocaleDateString(locale, {
day: 'numeric',
month: 'short',
...(sameYear ? {} : { year: 'numeric' }),
hour: '2-digit',
minute: '2-digit',
hour12,
})
}
export interface AdminStats {
totalUsers: number
totalTrips: number
+43
View File
@@ -701,6 +701,49 @@ describe('useAdmin', () => {
expect(toastCalls).toContainEqual({ type: 'success', message: 'User updated' });
});
it('FE-ADMHOOK-036d: the open users tab asks again who is online, without the spinner', async () => {
const ticks: Array<() => void> = [];
const spy = vi.spyOn(window, 'setInterval').mockImplementation(((fn: () => void) => {
ticks.push(fn);
return 0;
}) as unknown as typeof window.setInterval);
try {
const { result } = await mountAdmin();
expect(result.current.users[1].online).not.toBe(true);
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [me, { ...alice, online: true }] })));
await act(async () => {
ticks.forEach((tick) => tick());
});
await waitFor(() => expect(result.current.users[1].online).toBe(true));
expect(result.current.isLoading).toBe(false);
} finally {
spy.mockRestore();
}
});
it('FE-ADMHOOK-036c: a saved row keeps what the list derives (avatar, activity, online)', async () => {
server.use(
http.put('/api/admin/users/:id', ({ params }) =>
// The update answers with the account fields only.
HttpResponse.json({ user: { id: Number(params.id), username: 'alice2', email: 'a2@e.com', role: 'user', created_at: '2026-01-01 00:00:00' } })
)
);
const { result } = await mountAdmin();
const before = result.current.users[1];
act(() => result.current.handleEditUser(before));
act(() => result.current.setEditForm({ username: 'alice2', email: 'a2@e.com', role: 'user', password: '' }));
await act(async () => {
await result.current.handleSaveUser();
});
const after = result.current.users[1];
expect(after).toMatchObject({ username: 'alice2', email: 'a2@e.com' });
expect(after.last_login).toBe(before.last_login);
expect(after.online).toBe(before.online);
expect(after.avatar_url).toBe(before.avatar_url);
expect(after.created_at).toBe(before.created_at);
});
it('FE-ADMHOOK-037: handleSaveUser refuses a password shorter than eight characters', async () => {
let called = false;
server.use(
+37 -3
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import apiClient, { adminApi, authApi } from '../../api/client'
import { useAuthStore } from '../../store/authStore'
@@ -8,7 +8,7 @@ import { useTranslation } from '../../i18n'
import { getApiErrorMessage } from '../../types'
import { useToast } from '../../components/shared/Toast'
import { managedAdminTabs } from '../../managed'
import type { AdminUser, AdminStats, OidcConfig, UpdateInfo } from './adminModel'
import { mergeSavedUser, type AdminUser, type AdminStats, type OidcConfig, type UpdateInfo } from './adminModel'
import type { TransitProvider, TransitKeySource } from '@trek/shared'
import { passwordErrorKey } from '../../utils/passwordError'
@@ -35,6 +35,9 @@ const ADMIN_TAB_IDS = [
*/
const MANAGED_HIDDEN = ['storage', 'github', 'backup']
/** How often the open users list asks again who is online and active. */
const USERS_REFRESH_MS = 30_000
/**
* Admin page logic — owns every admin data slice (users, stats, invites, auth
* toggles, OIDC, feature flags, API keys, SMTP, version/update) plus the CRUD
@@ -246,6 +249,34 @@ export function useAdmin() {
}
}
// Who is online and when someone was last active change while the list is
// open; it was read once and went stale until a reload. Refreshed quietly
// while the users tab is in view, and at once when the page comes back.
// Bumped by every local change to the list; a refresh asked before one is out of date.
const usersWrites = useRef(0)
useEffect(() => {
if (activeTab !== 'users') return
let cancelled = false
const refresh = async () => {
if (document.visibilityState !== 'visible') return
const asked = usersWrites.current
try {
const data = await adminApi.users()
if (!cancelled && asked === usersWrites.current) setUsers(data.users)
} catch {
/* the list on screen stays; the next tick asks again */
}
}
const timer = window.setInterval(() => { void refresh() }, USERS_REFRESH_MS)
const onVisible = () => { void refresh() }
document.addEventListener('visibilitychange', onVisible)
return () => {
cancelled = true
window.clearInterval(timer)
document.removeEventListener('visibilitychange', onVisible)
}
}, [activeTab])
const loadAppConfig = async () => {
try {
const config = await authApi.getAppConfig()
@@ -420,6 +451,7 @@ export function useAdmin() {
}
try {
const data = await adminApi.createUser(createForm)
usersWrites.current += 1
setUsers(prev => [data.user, ...prev])
setShowCreateUser(false)
setCreateForm({ username: '', email: '', password: '', role: 'user' })
@@ -484,7 +516,8 @@ export function useAdmin() {
payload.password = editForm.password.trim()
}
const data = await adminApi.updateUser(editingUser.id, payload)
setUsers(prev => prev.map(u => u.id === editingUser.id ? data.user : u))
usersWrites.current += 1
setUsers(prev => prev.map(u => u.id === editingUser.id ? mergeSavedUser(u, data.user) : u))
setEditingUser(null)
toast.success(t('admin.toast.userUpdated'))
} catch (err: unknown) {
@@ -502,6 +535,7 @@ export function useAdmin() {
if (!opts.confirmed && !confirm(t('admin.deleteUser', { name: user.username }))) return
try {
await adminApi.deleteUser(user.id)
usersWrites.current += 1
setUsers(prev => prev.filter(u => u.id !== user.id))
toast.success(t('admin.toast.userDeleted'))
} catch (err: unknown) {