Merge fix/api-admin: QA round 2026-09-19 (dev team)
This commit is contained in:
commit
6a86f54e4c
7 files changed
+379
-36
No files matched your search
@@ -21,6 +21,11 @@ const LABELS = {
|
||||
'auth.register.denied': 'Signup refused',
|
||||
'auth.logout': 'Signed out',
|
||||
'auth.logout.all': 'Signed out everywhere',
|
||||
// Device pairing (Settings → "Pair the mobile app"): the code is minted in a signed-in browser
|
||||
// tab and redeemed by the app, so "ok" is the phone coming online, not a sign-in.
|
||||
'auth.pair.create': 'Created a pairing code',
|
||||
'auth.pair.ok': 'Paired a phone',
|
||||
'auth.pair.fail': 'Pairing failed',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.invite.create': 'Created an invite code',
|
||||
@@ -41,7 +46,9 @@ const REASONS = {
|
||||
'account-disabled': 'the account is disabled',
|
||||
'credential-exists': 'that passkey already belongs to a profile',
|
||||
'invite-invalid': 'the invite code was used or revoked in the meantime',
|
||||
'invite-rejected': 'wrong or already-used invite code'
|
||||
'invite-rejected': 'wrong or already-used invite code',
|
||||
'code-invalid': 'wrong or expired pairing code',
|
||||
'user-unavailable': 'the profile behind the pairing code is disabled or gone'
|
||||
}
|
||||
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
|
||||
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
|
||||
|
||||
// Every event name and reason code the server can emit (api/server.js, the audit block).
|
||||
// Every event name and reason code the server can emit, read off api/server.js itself rather
|
||||
// than kept as a second list here: the hand-kept copy silently missed the three pairing events
|
||||
// for several releases, and the dashboard printed 'auth.pair.create' at the operator (QA C18).
|
||||
// If a new one is added there without a label here, the first test fails rather than the
|
||||
// dashboard quietly printing a dotted identifier at a person.
|
||||
const EVENTS = [
|
||||
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
|
||||
'auth.register.denied', 'auth.logout', 'auth.logout.all',
|
||||
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
|
||||
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
|
||||
]
|
||||
const REASONS = [
|
||||
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
|
||||
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
|
||||
]
|
||||
const SERVER = readFileSync(new URL('../../../api/server.js', import.meta.url), 'utf8')
|
||||
const EVENTS = [...new Set([...SERVER.matchAll(/audit\(req, '([a-z.]+)'/g)].map(m => m[1]))]
|
||||
const REASONS = [...new Set([...SERVER.matchAll(/msg: '([a-z-]+)'/g)].map(m => m[1]))]
|
||||
|
||||
describe('auditLabel', () => {
|
||||
it('has a sentence for every event the server emits', () => {
|
||||
@@ -58,6 +54,14 @@ describe('auditReason', () => {
|
||||
})
|
||||
|
||||
describe('auditLine', () => {
|
||||
it('reads the server lists off api/server.js, pairing events included', () => {
|
||||
// Guards the extraction itself: an empty match would make the two loops above vacuous.
|
||||
expect(EVENTS).toEqual(expect.arrayContaining(['auth.login.ok', 'auth.pair.create', 'auth.pair.ok', 'auth.pair.fail', 'admin.audit.clear']))
|
||||
expect(REASONS).toEqual(expect.arrayContaining(['challenge-expired', 'code-invalid', 'user-unavailable']))
|
||||
expect(auditLine({ ev: 'auth.pair.fail', ok: false, msg: 'code-invalid' })).toEqual({ title: 'Pairing failed', sub: 'unknown caller · wrong or expired pairing code' })
|
||||
expect(auditLine({ ev: 'auth.pair.ok', ok: true, name: 'Verifier' })).toEqual({ title: 'Paired a phone', sub: 'Verifier' })
|
||||
})
|
||||
|
||||
it('names the person who did it', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
|
||||
.toEqual({ title: 'Signed in', sub: 'Duarte' })
|
||||
|
||||
@@ -36,6 +36,12 @@ function UserDetail({ id, onChanged, close }) {
|
||||
useEffect(() => { api('/api/admin/user?id=' + encodeURIComponent(id)).then(setD).catch(e => toast(e.message)) }, [id])
|
||||
if (!d) return <div className="muted small">Loading…</div>
|
||||
const u = d.user
|
||||
// The document comes straight off the user's state file. PUT /api/data drops null and
|
||||
// shapeless entries now, but a file written before it did still answers with them, and this
|
||||
// sheet renders outside the route's ErrorBoundary: one throw here blanked the whole app and
|
||||
// left exactly this account un-disableable. setsDone/workoutVolume walk entries and sets, so
|
||||
// an entry that lacks either has nothing to show and is skipped rather than drawn.
|
||||
const workouts = (d.workouts || []).filter(w => w && Array.isArray(w.entries) && w.entries.every(e => e && Array.isArray(e.sets)))
|
||||
const setDisabled = disabled => {
|
||||
api('/api/admin/user/disable', { method: 'POST', body: JSON.stringify({ id: u.id, disabled }) })
|
||||
.then(() => { toast(disabled ? 'User disabled' : 'User enabled'); onChanged(); close() })
|
||||
@@ -50,7 +56,7 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<span className="adm-pill">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
|
||||
</div>
|
||||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||||
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.workouts.length}</div></div>
|
||||
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{workouts.length}</div></div>
|
||||
<div className="tile"><div className="l">Weigh-ins</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.bodyweight.length}</div></div>
|
||||
<div className="tile"><div className="l">Routines</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.routines.length}</div></div>
|
||||
<div className="tile"><div className="l">Last sync</div><div className="v" style={{ fontSize: '.95rem' }}>{rel(d.lastSync)}</div></div>
|
||||
@@ -63,8 +69,8 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<div className="adm-hint">{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}</div>
|
||||
</>}
|
||||
<h4 className="sec">Workout history</h4>
|
||||
{d.workouts.length ? <div className="list" style={{ gap: 0 }}>
|
||||
{d.workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
{workouts.length ? <div className="list" style={{ gap: 0 }}>
|
||||
{workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
<div><div className="small" style={{ fontWeight: 600 }}>{w.name}</div>
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · ' + w.prs.length + ' PR' : ''}</div></div>
|
||||
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment happy-dom
|
||||
// The admin drill-down (QA C16): a profile whose stored workouts hold a null or otherwise
|
||||
// shapeless entry must still open, because the sheet host sits outside the route's
|
||||
// ErrorBoundary — a throw here blanked the whole app and left the account un-disableable.
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import Admin from './Admin.jsx'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const mocks = vi.hoisted(() => ({ answers: {}, sheets: [] }))
|
||||
vi.mock('../lib/api.js', () => ({
|
||||
api: path => {
|
||||
const key = path.split('?')[0]
|
||||
return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found'))
|
||||
}
|
||||
}))
|
||||
vi.mock('../store/useStore.js', () => {
|
||||
const snap = () => ({ user: { id: 'adm', name: 'Admin', admin: true }, S: {} })
|
||||
const useStore = selector => selector ? selector(snap()) : snap()
|
||||
useStore.getState = snap
|
||||
return { useStore }
|
||||
})
|
||||
vi.mock('../store/useUI.js', () => {
|
||||
const snap = () => ({ toast: () => {}, openSheet: render => mocks.sheets.push(render) })
|
||||
const useUI = selector => selector ? selector(snap()) : snap()
|
||||
useUI.getState = snap
|
||||
return { useUI }
|
||||
})
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
|
||||
vi.mock('./AdminCoach.jsx', () => ({ default: () => null }))
|
||||
|
||||
const mounted = []
|
||||
function render(el) {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(el))
|
||||
return host
|
||||
}
|
||||
const settle = () => act(() => new Promise(r => setTimeout(r, 0)))
|
||||
|
||||
const good = { id: 'w1', name: 'Push day', d: '2026-09-10', start: 1000, end: 61000, entries: [{ sets: [{ done: true }, { done: false }] }] }
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
mocks.sheets.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: [] },
|
||||
'/api/admin/audit': { rows: [] },
|
||||
'/api/admin/user': {
|
||||
user: { id: 'u1', name: 'Mallory', created: '2026-09-01T00:00:00Z', disabled: false, admin: false },
|
||||
unit: 'kg', lastSync: null, routines: [], bodyweight: [],
|
||||
// What GET /api/admin/user hands over for a document written before PUT /api/data dropped
|
||||
// such entries: a null, and a bare object without entries, next to a real session.
|
||||
workouts: [null, good, {}]
|
||||
}
|
||||
}
|
||||
})
|
||||
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
|
||||
|
||||
describe('Admin user drill-down', () => {
|
||||
it('opens a profile with malformed workout entries and still offers "Disable account"', async () => {
|
||||
const page = render(<Admin />)
|
||||
await settle()
|
||||
const row = [...page.querySelectorAll('.item')].find(el => el.textContent.includes('Mallory'))
|
||||
expect(row).toBeTruthy()
|
||||
act(() => row.click())
|
||||
expect(mocks.sheets.length).toBe(1)
|
||||
const sheet = render(mocks.sheets[0](() => {}))
|
||||
await settle()
|
||||
const buttons = [...sheet.querySelectorAll('button')].map(b => b.textContent)
|
||||
expect(buttons).toContain('Disable account')
|
||||
// The one real session is listed; the two shapeless entries are skipped, not drawn as blanks.
|
||||
const rows = [...sheet.querySelectorAll('.list > div')]
|
||||
expect(rows.length).toBe(1)
|
||||
expect(rows[0].textContent).toContain('Push day')
|
||||
expect(rows[0].textContent).toContain('1 sets')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user