update: Add Global Search on Header, Add Global Audit log for all actions.

This commit is contained in:
2026-04-19 15:41:29 +03:00
parent 4f35bef6e3
commit 6a958a8d7d
27 changed files with 2086 additions and 267 deletions
@@ -299,6 +299,7 @@ export default function DeviceDetail() {
onEditBacklight: () => setEditingBacklight(true),
onEditSubscription: () => setEditingSubscription(true),
onEditWarranty: () => setEditingWarranty(true),
onNavigateToManage: () => handleTabChange('manage'),
}
// ── Render ─────────────────────────────────────────────────────────────────
@@ -431,97 +431,7 @@ export default function ManageTab({ device, canEdit, deviceUsers: propUsers, use
</div>
</GlassCard>
{/* ── 2. DEVICE NOTES ───────────────────────────────────────────────── */}
<GlassCard>
<CardHeader
label="Device Notes"
count={notes.length || undefined}
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setNoteModal({ open: true, note: null })}>
+ Add Note
</Button>
)}
/>
<div style={{ padding: notesLoading || notes.length === 0 ? 0 : 'var(--space-4) var(--space-5)' }}>
{notesLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
<Spinner size="sm" />
</div>
) : notes.length === 0 ? (
<EmptySlate
icon={
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="16" y1="13" x2="8" y2="13"/>
<line x1="16" y1="17" x2="8" y2="17"/>
<polyline points="10 9 9 9 8 9"/>
</svg>
}
message="No notes recorded for this device yet."
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setNoteModal({ open: true, note: null })}>
Add first note
</Button>
)}
/>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 'var(--space-3)' }}>
{notes.map(note => (
<div
key={note.id}
className="manage-note-card"
style={{
display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
padding: 'var(--space-4)',
borderRadius: 'var(--radius-lg)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-sm)',
}}
>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.6, whiteSpace: 'pre-wrap', flex: 1 }}>
{note.content || '—'}
</p>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-2)' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }} title={fmtDateMedium(note.created_at)}>
{fmtRelative(note.created_at)}
</span>
{note.created_by && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{note.created_by}
</span>
)}
</div>
{canEdit && (
<div style={{ display: 'flex', gap: 'var(--space-1)', flexShrink: 0 }}>
<button onClick={() => setNoteModal({ open: true, note })} title="Edit note" aria-label="Edit note"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-primary)'; e.currentTarget.style.background = 'var(--color-primary-subtle)'; e.currentTarget.style.borderColor = 'rgba(192,193,255,0.25)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="edit" size={13} />
</button>
<button onClick={() => setConfirmDeleteNote(note)} title="Delete note" aria-label="Delete note"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'var(--color-danger-bg)'; e.currentTarget.style.borderColor = 'var(--color-danger)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="delete" size={13} />
</button>
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</GlassCard>
{/* ── 3. LINKED ISSUES ──────────────────────────────────────────────── */}
{/* ── 2. LINKED ISSUES ──────────────────────────────────────────────── */}
<GlassCard>
<CardHeader
label="Linked Issues"
@@ -605,6 +515,96 @@ export default function ManageTab({ device, canEdit, deviceUsers: propUsers, use
</div>
</GlassCard>
{/* ── 3. DEVICE NOTES ───────────────────────────────────────────────── */}
<GlassCard>
<CardHeader
label="Device Notes"
count={notes.length || undefined}
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setNoteModal({ open: true, note: null })}>
+ Add Note
</Button>
)}
/>
<div style={{ padding: notesLoading || notes.length === 0 ? 0 : 'var(--space-4) var(--space-5)' }}>
{notesLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
<Spinner size="sm" />
</div>
) : notes.length === 0 ? (
<EmptySlate
icon={
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="16" y1="13" x2="8" y2="13"/>
<line x1="16" y1="17" x2="8" y2="17"/>
<polyline points="10 9 9 9 8 9"/>
</svg>
}
message="No notes recorded for this device yet."
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setNoteModal({ open: true, note: null })}>
Add first note
</Button>
)}
/>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
{notes.map(note => (
<div
key={note.id}
className="manage-note-card"
style={{
display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
padding: 'var(--space-4)',
borderRadius: 'var(--radius-lg)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-sm)',
}}
>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
{note.content || '—'}
</p>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-2)' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }} title={fmtDateMedium(note.created_at)}>
{fmtRelative(note.created_at)}
</span>
{note.created_by && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{note.created_by}
</span>
)}
</div>
{canEdit && (
<div style={{ display: 'flex', gap: 'var(--space-1)', flexShrink: 0 }}>
<button onClick={() => setNoteModal({ open: true, note })} title="Edit note" aria-label="Edit note"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-primary)'; e.currentTarget.style.background = 'var(--color-primary-subtle)'; e.currentTarget.style.borderColor = 'rgba(192,193,255,0.25)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="edit" size={13} />
</button>
<button onClick={() => setConfirmDeleteNote(note)} title="Delete note" aria-label="Delete note"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'var(--color-danger-bg)'; e.currentTarget.style.borderColor = 'var(--color-danger)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="delete" size={13} />
</button>
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</GlassCard>
</div>
{/* ── Modals ─────────────────────────────────────────────────────────── */}
@@ -168,6 +168,7 @@ export default function OverviewTab({
setStaffNotes,
deviceUsers,
usersLoading,
onNavigateToManage,
}) {
const navigate = useNavigate()
const { toast } = useToast()
@@ -242,8 +243,27 @@ export default function OverviewTab({
useEffect(() => { loadNotes() }, [loadNotes])
const [issues, setIssues] = useState([])
const [issuesLoading, setIssuesLoading] = useState(false)
const loadIssues = useCallback(async () => {
if (!id) return
setIssuesLoading(true)
try {
const data = await api.get(`/notes/by-entity/device/${id}`)
setIssues(Array.isArray(data) ? data : [])
} catch {
setIssues([])
} finally {
setIssuesLoading(false)
}
}, [id])
useEffect(() => { loadIssues() }, [loadIssues])
const [noteModal, setNoteModal] = useState({ open: false })
const [issueModal, setIssueModal] = useState({ open: false, entry: null })
const [viewNote, setViewNote] = useState(null)
const handleNoteSaved = () => {
setNoteModal({ open: false })
@@ -252,6 +272,7 @@ export default function OverviewTab({
const handleIssueSaved = () => {
setIssueModal({ open: false, entry: null })
loadIssues()
}
// ── Live logs ─────────────────────────────────────────────────────────────
@@ -708,7 +729,7 @@ export default function OverviewTab({
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-3)' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
<SectionLabel>Issues &amp; Notes</SectionLabel>
{notes.length > 0 && (
{(notes.length + issues.length) > 0 && (
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
@@ -717,22 +738,28 @@ export default function OverviewTab({
borderRadius: 'var(--radius-full)',
border: '1px solid var(--color-border)',
}}>
{notes.length}
{notes.length + issues.length}
</span>
)}
</div>
{canEdit && (
<div style={{ display: 'flex', gap: 'var(--space-2)', flexShrink: 0 }}>
<Button variant="ghost" size="sm" icon={<Icon name="plus" size={12} />} onClick={() => setNoteModal({ open: true })}>
Add Note
</Button>
<Button variant="ghost" size="sm" icon={<Icon name="plus" size={12} />} onClick={() => setIssueModal({ open: true, entry: null })}>
Record Issue
</Button>
</div>
)}
<div style={{ display: 'flex', gap: 'var(--space-2)', flexShrink: 0 }}>
{canEdit && (
<>
<Button variant="ghost" size="sm" icon={<Icon name="plus" size={12} />} onClick={() => setNoteModal({ open: true })}>
Add Note
</Button>
<Button variant="ghost" size="sm" icon={<Icon name="plus" size={12} />} onClick={() => setIssueModal({ open: true, entry: null })}>
Record Issue
</Button>
</>
)}
<Button variant="ghost" size="sm" onClick={onNavigateToManage}>
Edit
</Button>
</div>
</div>
{/* Notes */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
{notesLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
@@ -743,24 +770,42 @@ export default function OverviewTab({
No notes for this device.
</p>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 'var(--space-3)' }}>
<div style={{
display: 'grid',
gridTemplateColumns: notes.length === 1 ? '1fr' : notes.length === 2 ? '1fr 1fr' : 'repeat(3, 1fr)',
gap: 'var(--space-3)',
}}>
{notes.map((note, i) => (
<div
key={note.id || i}
onClick={() => setViewNote(note)}
style={{
padding: 'var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
cursor: 'pointer',
transition: 'border-color 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--color-border-strong)'}
onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--color-border)'}
>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.5, marginBottom: note.created_at ? 'var(--space-2)' : 0 }}>
<p style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-primary)',
lineHeight: 1.5,
marginBottom: note.created_at ? 'var(--space-2)' : 0,
overflow: 'hidden',
display: '-webkit-box',
WebkitLineClamp: 3,
WebkitBoxOrient: 'vertical',
}}>
{note.content || note.text || '—'}
</p>
{note.created_at && (
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{fmtRelative(note.created_at)}
{note.author_name ? ` · ${note.author_name}` : ''}
{note.created_by ? ` · ${note.created_by}` : ''}
</p>
)}
</div>
@@ -768,6 +813,72 @@ export default function OverviewTab({
</div>
)}
</div>
{/* Issues */}
{(issuesLoading || issues.length > 0) && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', borderTop: '1px solid var(--color-border)', paddingTop: 'var(--space-3)' }}>
<SectionLabel>Linked Issues</SectionLabel>
{issuesLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
<Spinner size="sm" />
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
{issues.map((issue, i) => {
const statusColors = {
open: { color: 'var(--color-danger)', bg: 'var(--color-danger-bg)' },
researching: { color: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
resolved: { color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
}
const sc = statusColors[issue.status] || statusColors.open
return (
<div
key={issue.id || i}
onClick={() => setIssueModal({ open: true, entry: issue })}
style={{
display: 'flex',
alignItems: 'center',
gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
cursor: 'pointer',
transition: 'border-color 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--color-border-strong)'}
onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--color-border)'}
>
<span style={{
display: 'inline-flex', alignItems: 'center', gap: 5,
padding: '2px 8px',
borderRadius: 'var(--radius-full)',
backgroundColor: sc.bg,
border: `1px solid ${sc.color}33`,
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: sc.color,
whiteSpace: 'nowrap',
flexShrink: 0,
}}>
<span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: sc.color, flexShrink: 0 }} />
{issue.status || 'open'}
</span>
<span style={{ flex: 1, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{issue.title}
</span>
{issue.created_at && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }}>
{fmtRelative(issue.created_at)}
</span>
)}
</div>
)
})}
</div>
)}
</div>
)}
</GlassCard>
</div>
@@ -1047,13 +1158,72 @@ export default function OverviewTab({
<EntryFormModal
open={issueModal.open}
entry={null}
entry={issueModal.entry}
defaultType="issue"
prefilledLinks={[{ entity_type: 'device', entity_id: id, display_name: device?.device_name || sn, locked: true }]}
prefilledLinks={issueModal.entry ? undefined : [{ entity_type: 'device', entity_id: id, display_name: device?.device_name || sn, locked: true }]}
knownEntities={id ? { [id]: device?.device_name || sn } : undefined}
onClose={() => setIssueModal({ open: false, entry: null })}
onSaved={handleIssueSaved}
/>
{/* ── Note full-view mini modal ──────────────────────────────────────── */}
{viewNote && (
<div
onClick={() => setViewNote(null)}
style={{
position: 'fixed', inset: 0, zIndex: 9999,
background: 'rgba(0,0,0,0.55)',
backdropFilter: 'blur(4px)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: 'var(--space-6)',
}}
>
<div
onClick={e => e.stopPropagation()}
style={{
background: 'var(--color-bg-card)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-xl)',
boxShadow: 'var(--shadow-xl)',
maxWidth: 560,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 0,
overflow: 'hidden',
}}
>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: 'var(--space-4) var(--space-5)',
borderBottom: '1px solid var(--color-border)',
}}>
<SectionLabel>Note</SectionLabel>
<button
onClick={() => setViewNote(null)}
style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-text-muted)', display: 'flex', alignItems: 'center', padding: 4, borderRadius: 'var(--radius-sm)' }}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
<div style={{ padding: 'var(--space-5)', overflowY: 'auto', maxHeight: '60vh' }}>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
{viewNote.content || viewNote.text || '—'}
</p>
</div>
{viewNote.created_at && (
<div style={{ padding: 'var(--space-3) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{fmtRelative(viewNote.created_at)}
{viewNote.created_by ? ` · ${viewNote.created_by}` : ''}
</span>
</div>
)}
</div>
</div>
)}
</div>
)
}
@@ -844,8 +844,8 @@ function StepFlash({ device, bespokeOverride, onFlashed }) {
? `/api/manufacturing/devices/${sn}/partitions.bin?hw_type_override=${bespokeOverride.hwFamily}`
: `/api/manufacturing/devices/${sn}/partitions.bin`
const nvsUrl = bespokeOverride
? `/api/manufacturing/devices/${sn}/nvs.bin?hw_type_override=${bespokeOverride.hwFamily}&hw_revision_override=1.0&nvs_profile=${nvsProfile}`
: `/api/manufacturing/devices/${sn}/nvs.bin?nvs_profile=${nvsProfile}`
? `/api/manufacturing/devices/${sn}/nvs.bin?hw_type_override=${bespokeOverride.hwFamily}&hw_revision_override=1.0&nvs_schema=${nvsProfile}`
: `/api/manufacturing/devices/${sn}/nvs.bin?nvs_schema=${nvsProfile}`
const fwUrl = bespokeOverride
? `/api/firmware/bespoke/${bespokeOverride.firmware.channel}/${bespokeOverride.firmware.version}/firmware.bin`
: `/api/manufacturing/devices/${sn}/firmware.bin`
@@ -1037,17 +1037,15 @@ function StepFlash({ device, bespokeOverride, onFlashed }) {
{error && <div style={{ marginBottom: 'var(--space-3)' }}><ErrorBox msg={error} /></div>}
{/* Progress bars — shown while flashing */}
{(flashing || blProgress > 0) && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)', marginBottom: 'var(--space-3)' }}>
<div style={{ display: 'flex', gap: 'var(--space-4)' }}>
<ProgressBar flex label="Bootloader (0x1000)" percent={blProgress} />
<ProgressBar flex label="Partition Table (0x8000)" percent={partProgress} />
</div>
<ProgressBar label="NVS (0x9000)" percent={nvsProgress} />
<ProgressBar label="Firmware (0x10000)" percent={fwProgress} />
{/* Progress bars — always visible, idle at 0% */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)', marginBottom: 'var(--space-3)' }}>
<div style={{ display: 'flex', gap: 'var(--space-4)' }}>
<ProgressBar flex label="Bootloader (0x1000)" percent={blProgress} />
<ProgressBar flex label="Partition Table (0x8000)" percent={partProgress} />
</div>
)}
<ProgressBar label="NVS (0x9000)" percent={nvsProgress} />
<ProgressBar label="Firmware (0x10000)" percent={fwProgress} />
</div>
{/* Spacer */}
<div style={{ flex: 1 }} />
@@ -1109,7 +1107,7 @@ function StepFlash({ device, bespokeOverride, onFlashed }) {
border: '1px solid var(--color-border)',
overflow: 'hidden',
display: 'flex', flexDirection: 'column',
height: 320,
minHeight: 320,
}}>
<div style={{
padding: '8px 12px',
@@ -0,0 +1,754 @@
// frontend/src/pages/settings/LogViewerPage.jsx
// Audit log viewer — filterable, paginated, expandable rows.
// Route: /settings/audit-log (wired in router/index.jsx)
import { useState, useEffect, useCallback, useRef } from 'react'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import PageHeader from '@/components/ui/PageHeader'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Pagination from '@/components/ui/Pagination'
import SearchBar from '@/components/ui/SearchBar'
import Select from '@/components/ui/Select'
import Button from '@/components/ui/Button'
import { fmtDateTimeMedium } from '@/lib/formatters'
// ─── Constants ────────────────────────────────────────────────────────────────
const PAGE_SIZE = 50
const ACTION_META = {
CREATE: { label: 'Create', variant: 'success' },
UPDATE: { label: 'Update', variant: 'info' },
DELETE: { label: 'Delete', variant: 'danger' },
COMMAND: { label: 'Command', variant: 'warning' },
PUBLISH: { label: 'Publish', variant: 'success' },
UNPUBLISH: { label: 'Unpublish', variant: 'neutral' },
LOGIN: { label: 'Login', variant: 'neutral' },
LOGOUT: { label: 'Logout', variant: 'neutral' },
PERMISSION_CHANGE:{ label: 'Permissions', variant: 'warning' },
STATUS_CHANGE: { label: 'Status Change', variant: 'info' },
}
const ENTITY_LABELS = {
customer: 'Customer',
order: 'Order',
device: 'Device',
melody: 'Melody',
product: 'Product',
staff: 'Staff',
ticket: 'Ticket',
note: 'Note',
quotation: 'Quotation',
firmware: 'Firmware',
archetype: 'Archetype',
}
const ACTION_OPTIONS = [
{ value: '', label: 'All Actions' },
{ value: 'CREATE', label: 'Create' },
{ value: 'UPDATE', label: 'Update' },
{ value: 'DELETE', label: 'Delete' },
{ value: 'COMMAND', label: 'Command' },
{ value: 'PUBLISH', label: 'Publish' },
{ value: 'UNPUBLISH', label: 'Unpublish' },
{ value: 'LOGIN', label: 'Login' },
{ value: 'LOGOUT', label: 'Logout' },
{ value: 'PERMISSION_CHANGE', label: 'Permissions' },
{ value: 'STATUS_CHANGE', label: 'Status Change' },
]
const ENTITY_OPTIONS = [
{ value: '', label: 'All Entities' },
...Object.entries(ENTITY_LABELS).map(([k, v]) => ({ value: k, label: v })),
]
// ─── Helpers ─────────────────────────────────────────────────────────────────
function actionMeta(action) {
return ACTION_META[action] ?? { label: action, variant: 'neutral' }
}
function buildParams({ actorId, action, entityType, fromDate, toDate, offset }) {
const p = new URLSearchParams()
if (actorId) p.set('actor_id', actorId)
if (action) p.set('action', action)
if (entityType) p.set('entity_type', entityType)
if (fromDate) p.set('from_date', new Date(fromDate).toISOString())
if (toDate) p.set('to_date', new Date(toDate + 'T23:59:59').toISOString())
p.set('limit', String(PAGE_SIZE))
p.set('offset', String(offset))
return p.toString()
}
// ─── Changes diff renderer ────────────────────────────────────────────────────
function ChangesDiff({ changes }) {
if (!changes || Object.keys(changes).length === 0) return null
return (
<div style={{
display: 'flex',
flexDirection: 'column',
gap: 'var(--space-1)',
marginTop: 'var(--space-3)',
}}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
marginBottom: 'var(--space-1)',
}}>
Changes
</span>
{Object.entries(changes).map(([field, { old: oldVal, new: newVal }]) => (
<div key={field} style={{
display: 'grid',
gridTemplateColumns: '140px 1fr 1fr',
gap: 'var(--space-2)',
alignItems: 'start',
fontSize: 'var(--font-size-sm)',
padding: 'var(--space-2) var(--space-3)',
backgroundColor: 'var(--color-bg-abyss)',
borderRadius: 'var(--radius-sm)',
}}>
<span style={{
fontFamily: 'var(--font-family-mono)',
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
wordBreak: 'break-all',
}}>
{field}
</span>
<span style={{
color: 'var(--color-danger)',
wordBreak: 'break-all',
fontFamily: oldVal !== null && typeof oldVal === 'string' ? undefined : 'var(--font-family-mono)',
fontSize: 'var(--font-size-xs)',
}}>
{oldVal === null || oldVal === undefined ? <em style={{ color: 'var(--color-text-muted)' }}>null</em> : String(oldVal)}
</span>
<span style={{
color: 'var(--color-success)',
wordBreak: 'break-all',
fontFamily: newVal !== null && typeof newVal === 'string' ? undefined : 'var(--font-family-mono)',
fontSize: 'var(--font-size-xs)',
}}>
{newVal === null || newVal === undefined ? <em style={{ color: 'var(--color-text-muted)' }}>null</em> : String(newVal)}
</span>
</div>
))}
</div>
)
}
// ─── Meta renderer ────────────────────────────────────────────────────────────
function MetaBlock({ meta }) {
if (!meta || Object.keys(meta).length === 0) return null
return (
<div style={{ marginTop: 'var(--space-3)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
display: 'block',
marginBottom: 'var(--space-1)',
}}>
Context
</span>
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: 'var(--space-2)',
}}>
{Object.entries(meta).map(([k, v]) => (
<span key={k} style={{
display: 'inline-flex',
alignItems: 'center',
gap: 'var(--space-1)',
fontSize: 'var(--font-size-xs)',
padding: '2px var(--space-2)',
backgroundColor: 'var(--color-bg-abyss)',
borderRadius: 'var(--radius-sm)',
color: 'var(--color-text-secondary)',
}}>
<span style={{ color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>{k}</span>
<span style={{ color: 'var(--color-text-muted)' }}>·</span>
<span style={{ fontFamily: 'var(--font-family-mono)' }}>{String(v)}</span>
</span>
))}
</div>
</div>
)
}
// ─── Row ──────────────────────────────────────────────────────────────────────
function LogRow({ entry, isExpanded, onToggle }) {
const { label, variant } = actionMeta(entry.action)
const entityLabel = ENTITY_LABELS[entry.entity_type] ?? entry.entity_type
const hasDetail = (entry.changes && Object.keys(entry.changes).length > 0)
|| (entry.meta && Object.keys(entry.meta).length > 0)
return (
<>
<tr
className={`log-row${isExpanded ? ' log-row--expanded' : ''}${hasDetail ? ' log-row--clickable' : ''}`}
onClick={hasDetail ? onToggle : undefined}
style={{ cursor: hasDetail ? 'pointer' : 'default' }}
>
{/* Timestamp */}
<td className="log-cell log-cell--ts">
<span style={{
fontFamily: 'var(--font-family-mono)',
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
whiteSpace: 'nowrap',
}}>
{fmtDateTimeMedium(entry.occurred_at)}
</span>
</td>
{/* Actor */}
<td className="log-cell">
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
<div style={{
width: 24,
height: 24,
borderRadius: 'var(--radius-full)',
background: 'var(--color-primary-subtle)',
border: '1px solid rgba(192,193,255,0.12)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
fontFamily: 'var(--font-family-display)',
fontWeight: 'var(--font-weight-semibold)',
fontSize: '10px',
color: 'var(--color-primary)',
letterSpacing: '0.02em',
}}>
{entry.actor_name?.charAt(0)?.toUpperCase() ?? '?'}
</div>
<span style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-primary)',
fontWeight: 'var(--font-weight-medium)',
}}>
{entry.actor_name}
</span>
</div>
</td>
{/* Action badge */}
<td className="log-cell">
<StatusBadge variant={variant}>{label}</StatusBadge>
</td>
{/* Entity */}
<td className="log-cell">
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
fontWeight: 'var(--font-weight-semibold)',
}}>
{entityLabel}
</span>
{entry.entity_label && (
<span style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-primary)',
fontWeight: 'var(--font-weight-medium)',
}}>
{entry.entity_label}
</span>
)}
</div>
</td>
{/* Entity ID */}
<td className="log-cell log-cell--id">
<span style={{
fontFamily: 'var(--font-family-mono)',
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
}}>
{entry.entity_id?.length > 16
? entry.entity_id.slice(0, 8) + '…' + entry.entity_id.slice(-4)
: entry.entity_id}
</span>
</td>
{/* Expand chevron */}
<td className="log-cell log-cell--expand" style={{ textAlign: 'right', width: 32 }}>
{hasDetail && (
<svg
width="12" height="12" viewBox="0 0 12 12" fill="none"
stroke="currentColor" strokeWidth="1.8"
strokeLinecap="round" strokeLinejoin="round"
aria-hidden="true"
style={{
display: 'block',
marginLeft: 'auto',
color: 'var(--color-text-muted)',
transform: isExpanded ? 'rotate(180deg)' : 'none',
transition: 'transform 150ms ease',
}}
>
<path d="M2 4l4 4 4-4" />
</svg>
)}
</td>
</tr>
{/* Expanded detail row */}
{isExpanded && hasDetail && (
<tr className="log-row-detail">
<td colSpan={6} style={{ padding: 0 }}>
<div style={{
padding: 'var(--space-4) var(--space-6)',
backgroundColor: 'var(--color-bg-void)',
borderBottom: '1px solid var(--color-border)',
}}>
<ChangesDiff changes={entry.changes} />
<MetaBlock meta={entry.meta} />
</div>
</td>
</tr>
)}
</>
)
}
// ─── Skeleton ─────────────────────────────────────────────────────────────────
function SkeletonRows() {
return Array.from({ length: 10 }).map((_, i) => (
<tr key={i} className="log-row">
{[140, 120, 80, 140, 100, 24].map((w, j) => (
<td key={j} className="log-cell">
<div style={{
height: 14,
width: w,
maxWidth: '100%',
borderRadius: 'var(--radius-sm)',
backgroundColor: 'var(--color-bg-elevated)',
opacity: 0.6,
}} />
</td>
))}
</tr>
))
}
// ─── Filters bar ──────────────────────────────────────────────────────────────
function FiltersBar({ filters, setFilters, staffList, onReset }) {
const hasFilters = filters.actorId || filters.action || filters.entityType
|| filters.fromDate || filters.toDate
return (
<div style={{
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
gap: 'var(--space-3)',
}}>
{/* Actor / staff member */}
<div style={{ minWidth: 160 }}>
<Select
value={filters.actorId}
onChange={(e) => setFilters(f => ({ ...f, actorId: e.target.value, offset: 0 }))}
placeholder="All Staff"
>
<option value="">All Staff</option>
{staffList.map(s => (
<option key={s.id} value={s.id}>{s.name}</option>
))}
</Select>
</div>
{/* Action */}
<div style={{ minWidth: 140 }}>
<Select
value={filters.action}
onChange={(e) => setFilters(f => ({ ...f, action: e.target.value, offset: 0 }))}
placeholder="All Actions"
>
{ACTION_OPTIONS.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</Select>
</div>
{/* Entity type */}
<div style={{ minWidth: 140 }}>
<Select
value={filters.entityType}
onChange={(e) => setFilters(f => ({ ...f, entityType: e.target.value, offset: 0 }))}
placeholder="All Entities"
>
{ENTITY_OPTIONS.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</Select>
</div>
{/* Date range */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
<input
type="date"
value={filters.fromDate}
onChange={(e) => setFilters(f => ({ ...f, fromDate: e.target.value, offset: 0 }))}
aria-label="From date"
className="log-date-input"
/>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>–</span>
<input
type="date"
value={filters.toDate}
onChange={(e) => setFilters(f => ({ ...f, toDate: e.target.value, offset: 0 }))}
aria-label="To date"
className="log-date-input"
/>
</div>
{/* Reset */}
{hasFilters && (
<Button variant="ghost" size="sm" onClick={onReset}>
Clear filters
</Button>
)}
</div>
)
}
// ─── Summary stats ────────────────────────────────────────────────────────────
function StatPill({ label, value, variant }) {
const colors = {
success: 'var(--color-success)',
danger: 'var(--color-danger)',
warning: 'var(--color-warning)',
info: 'var(--color-info)',
neutral: 'var(--color-text-muted)',
}
return (
<div style={{
display: 'flex',
alignItems: 'center',
gap: 'var(--space-2)',
padding: 'var(--space-2) var(--space-3)',
backgroundColor: 'var(--color-bg-surface)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-md)',
minWidth: 80,
}}>
<span style={{
width: 6,
height: 6,
borderRadius: 'var(--radius-full)',
backgroundColor: colors[variant] ?? colors.neutral,
flexShrink: 0,
}} />
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
fontWeight: 'var(--font-weight-semibold)',
}}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-primary)',
fontFamily: 'var(--font-family-mono)',
marginLeft: 'auto',
}}>
{value}
</span>
</div>
)
}
// ─── Main page ────────────────────────────────────────────────────────────────
const INITIAL_FILTERS = {
actorId: '',
action: '',
entityType: '',
fromDate: '',
toDate: '',
offset: 0,
}
export default function LogViewerPage() {
const { user } = useAuth()
const [entries, setEntries] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [total, setTotal] = useState(null)
const [staffList, setStaffList] = useState([])
const [filters, setFilters] = useState(INITIAL_FILTERS)
const [expandedId, setExpandedId] = useState(null)
const [stats, setStats] = useState(null)
// Derived pagination
const page = Math.floor(filters.offset / PAGE_SIZE) + 1
const pageCount = total != null ? Math.ceil(total / PAGE_SIZE) : 0
// Load staff list once for the actor dropdown
useEffect(() => {
api.get('/staff').then(data => {
setStaffList((data.staff ?? data ?? []).map(s => ({ id: s.id, name: s.name })))
}).catch(() => {})
}, [])
// Load entries whenever filters change
const fetchEntries = useCallback(async () => {
setLoading(true)
setError(null)
setExpandedId(null)
try {
const qs = buildParams(filters)
const data = await api.get(`/audit-log?${qs}`)
const rows = data.entries ?? []
setEntries(rows)
// The API doesn't return total — fetch count via a separate offset-trick:
// if we got a full page, there may be more; signal unknown total for now.
setTotal(null)
// Build quick stats from current page
const actionCounts = {}
rows.forEach(r => { actionCounts[r.action] = (actionCounts[r.action] ?? 0) + 1 })
setStats(actionCounts)
} catch (err) {
setError(err?.message ?? 'Failed to load audit log.')
} finally {
setLoading(false)
}
}, [filters])
useEffect(() => { fetchEntries() }, [fetchEntries])
function handleReset() {
setFilters(INITIAL_FILTERS)
}
function toggleExpand(id) {
setExpandedId(prev => prev === id ? null : id)
}
// ── Render states ────────────────────────────────────────────────────────
const isEmpty = !loading && !error && entries.length === 0
return (
<>
<style>{`
.log-row {
border-bottom: 1px solid var(--color-border);
transition: background-color 80ms;
}
.log-row:hover {
background-color: var(--color-bg-elevated);
}
.log-row--expanded {
background-color: var(--color-bg-elevated);
}
.log-row--clickable:hover {
background-color: var(--color-bg-island);
}
.log-row-detail {
background-color: var(--color-bg-void);
}
.log-cell {
padding: var(--space-3) var(--space-4);
vertical-align: middle;
}
.log-cell--ts {
width: 148px;
white-space: nowrap;
}
.log-cell--id {
width: 120px;
}
.log-cell--expand {
width: 40px;
padding-right: var(--space-4);
}
.log-table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
.log-table thead th {
padding: var(--space-2) var(--space-4);
text-align: left;
font-size: var(--font-size-xs);
font-weight: var(--font-weight-semibold);
color: var(--color-text-muted);
text-transform: uppercase;
letter-spacing: var(--tracking-wide);
border-bottom: 1px solid var(--color-border-strong);
white-space: nowrap;
background-color: var(--color-bg-void);
}
.log-date-input {
height: 32px;
padding: 0 var(--space-3);
background-color: var(--color-bg-abyss);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
color: var(--color-text-primary);
font-size: var(--font-size-sm);
font-family: var(--font-family-base);
outline: none;
transition: border-color 150ms;
color-scheme: dark;
}
.log-date-input:focus {
border-color: var(--color-border-focus);
box-shadow: var(--shadow-focus);
}
.log-date-input::-webkit-calendar-picker-indicator {
filter: invert(0.6);
cursor: pointer;
}
`}</style>
<div className="page-wrapper">
<PageHeader
title="Log Viewer"
subtitle="Staff actions and system events across the console"
/>
{/* ── Stats strip ─────────────────────────────────────────────── */}
{stats && Object.keys(stats).length > 0 && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)' }}>
{Object.entries(stats)
.sort((a, b) => b[1] - a[1])
.map(([action, count]) => {
const { label, variant } = actionMeta(action)
return <StatPill key={action} label={label} value={count} variant={variant} />
})}
</div>
)}
{/* ── Filters ──────────────────────────────────────────────────── */}
<FiltersBar
filters={filters}
setFilters={setFilters}
staffList={staffList}
onReset={handleReset}
/>
{/* ── Table ────────────────────────────────────────────────────── */}
<div style={{
backgroundColor: 'var(--color-bg-surface)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-lg)',
overflow: 'hidden',
boxShadow: 'var(--shadow-card)',
}}>
<table className="log-table" aria-label="Audit log">
<thead>
<tr>
<th style={{ width: 148 }}>Timestamp</th>
<th style={{ width: 160 }}>Staff</th>
<th style={{ width: 110 }}>Action</th>
<th>Entity</th>
<th style={{ width: 120 }}>ID</th>
<th style={{ width: 40 }} />
</tr>
</thead>
<tbody>
{loading ? (
<SkeletonRows />
) : error ? (
<tr>
<td colSpan={6} style={{ padding: 'var(--space-12)', textAlign: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ color: 'var(--color-danger)', opacity: 0.7 }}>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4M12 16h.01" />
</svg>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
<Button variant="ghost" size="sm" onClick={fetchEntries}>Retry</Button>
</div>
</td>
</tr>
) : isEmpty ? (
<tr>
<td colSpan={6} style={{ padding: 'var(--space-12)', textAlign: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ color: 'var(--color-text-muted)' }}>
<rect x="3" y="3" width="18" height="18" rx="2" />
<path d="M8 9h8M8 13h5" />
</svg>
<p style={{ fontSize: 'var(--font-size-base)', color: 'var(--color-text-muted)' }}>
No entries match these filters
</p>
<Button variant="ghost" size="sm" onClick={handleReset}>
Clear filters
</Button>
</div>
</td>
</tr>
) : (
entries.map(entry => (
<LogRow
key={entry.id}
entry={entry}
isExpanded={expandedId === entry.id}
onToggle={() => toggleExpand(entry.id)}
/>
))
)}
</tbody>
</table>
</div>
{/* ── Pagination ────────────────────────────────────────────────── */}
{!loading && !error && entries.length > 0 && (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-4)' }}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
Showing {filters.offset + 1}–{filters.offset + entries.length}
{entries.length === PAGE_SIZE && ' · more available'}
</span>
<div style={{ display: 'flex', gap: 'var(--space-2)' }}>
<Button
variant="secondary"
size="sm"
disabled={filters.offset === 0}
onClick={() => setFilters(f => ({ ...f, offset: Math.max(0, f.offset - PAGE_SIZE) }))}
>
← Previous
</Button>
<Button
variant="secondary"
size="sm"
disabled={entries.length < PAGE_SIZE}
onClick={() => setFilters(f => ({ ...f, offset: f.offset + PAGE_SIZE }))}
>
Next →
</Button>
</div>
</div>
)}
</div>
</>
)
}