Start Magent beta overhaul
This commit is contained in:
@@ -0,0 +1,632 @@
|
||||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { authFetch, getApiBase, getToken, clearToken, getEventStreamToken } from './lib/auth'
|
||||
|
||||
const normalizeRecentResults = (items: any[]) =>
|
||||
items
|
||||
.filter((item: any) => item?.id)
|
||||
.map((item: any) => {
|
||||
const id = item.id
|
||||
const rawTitle = item.title
|
||||
const placeholder =
|
||||
typeof rawTitle === 'string' && rawTitle.trim().toLowerCase() === `request ${id}`
|
||||
return {
|
||||
id,
|
||||
title: !rawTitle || placeholder ? `Request #${id}` : rawTitle,
|
||||
year: item.year,
|
||||
statusLabel: item.statusLabel,
|
||||
artwork: item.artwork,
|
||||
createdAt: item.createdAt ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
const REQUEST_STAGE_OPTIONS = [
|
||||
{ value: 'all', label: 'All stages' },
|
||||
{ value: 'pending', label: 'Waiting' },
|
||||
{ value: 'approved', label: 'Approved' },
|
||||
{ value: 'in_progress', label: 'In progress' },
|
||||
{ value: 'working', label: 'Working' },
|
||||
{ value: 'partial', label: 'Partial' },
|
||||
{ value: 'ready', label: 'Ready' },
|
||||
{ value: 'declined', label: 'Declined' },
|
||||
]
|
||||
|
||||
export default function HomePage() {
|
||||
const router = useRouter()
|
||||
const [query, setQuery] = useState('')
|
||||
const [recent, setRecent] = useState<
|
||||
{
|
||||
id: number
|
||||
title: string
|
||||
year?: number
|
||||
statusLabel?: string
|
||||
artwork?: { poster_url?: string }
|
||||
createdAt?: string | null
|
||||
}[]
|
||||
>([])
|
||||
const [recentError, setRecentError] = useState<string | null>(null)
|
||||
const [recentLoading, setRecentLoading] = useState(false)
|
||||
const [searchResults, setSearchResults] = useState<
|
||||
{
|
||||
title: string
|
||||
year?: number
|
||||
type?: string
|
||||
requestId?: number
|
||||
statusLabel?: string
|
||||
requestedBy?: string | null
|
||||
accessible?: boolean
|
||||
}[]
|
||||
>([])
|
||||
const [searchError, setSearchError] = useState<string | null>(null)
|
||||
const [role, setRole] = useState<string | null>(null)
|
||||
const [recentDays, setRecentDays] = useState(90)
|
||||
const [recentStage, setRecentStage] = useState('all')
|
||||
const [authReady, setAuthReady] = useState(false)
|
||||
const [servicesStatus, setServicesStatus] = useState<
|
||||
{ overall: string; services: { name: string; status: string; message?: string }[] } | null
|
||||
>(null)
|
||||
const [servicesLoading, setServicesLoading] = useState(false)
|
||||
const [servicesError, setServicesError] = useState<string | null>(null)
|
||||
const [serviceTesting, setServiceTesting] = useState<Record<string, boolean>>({})
|
||||
const [serviceTestResults, setServiceTestResults] = useState<Record<string, string | null>>({})
|
||||
const [liveStreamConnected, setLiveStreamConnected] = useState(false)
|
||||
|
||||
const submit = (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
const trimmed = query.trim()
|
||||
if (!trimmed) return
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
router.push(`/requests/${encodeURIComponent(trimmed)}`)
|
||||
return
|
||||
}
|
||||
void runSearch(trimmed)
|
||||
}
|
||||
|
||||
const toServiceSlug = (name: string) => name.toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
|
||||
const updateServiceStatus = (name: string, status: string, message?: string) => {
|
||||
setServicesStatus((prev) => {
|
||||
if (!prev) return prev
|
||||
return {
|
||||
...prev,
|
||||
services: prev.services.map((service) =>
|
||||
service.name === name ? { ...service, status, message } : service
|
||||
),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const testService = async (name: string) => {
|
||||
const slug = toServiceSlug(name)
|
||||
setServiceTesting((prev) => ({ ...prev, [name]: true }))
|
||||
setServiceTestResults((prev) => ({ ...prev, [name]: null }))
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const response = await authFetch(`${baseUrl}/status/services/${slug}/test`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
const text = await response.text()
|
||||
throw new Error(text || `Service test failed: ${response.status}`)
|
||||
}
|
||||
const data = await response.json()
|
||||
const status = data?.status ?? 'unknown'
|
||||
const message =
|
||||
data?.message ||
|
||||
(status === 'up'
|
||||
? 'API OK'
|
||||
: status === 'down'
|
||||
? 'API unreachable'
|
||||
: status === 'degraded'
|
||||
? 'Health warnings'
|
||||
: status === 'not_configured'
|
||||
? 'Not configured'
|
||||
: 'Unknown')
|
||||
setServiceTestResults((prev) => ({ ...prev, [name]: message }))
|
||||
updateServiceStatus(name, status, data?.message)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
setServiceTestResults((prev) => ({ ...prev, [name]: 'Test failed' }))
|
||||
} finally {
|
||||
setServiceTesting((prev) => ({ ...prev, [name]: false }))
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
const load = async () => {
|
||||
setRecentLoading(true)
|
||||
setRecentError(null)
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const meResponse = await authFetch(`${baseUrl}/auth/me`)
|
||||
if (!meResponse.ok) {
|
||||
if (meResponse.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
throw new Error(`Auth failed: ${meResponse.status}`)
|
||||
}
|
||||
const me = await meResponse.json()
|
||||
const userRole = me?.role ?? null
|
||||
setRole(userRole)
|
||||
setAuthReady(true)
|
||||
const take = userRole === 'admin' ? 50 : 6
|
||||
const params = new URLSearchParams({
|
||||
take: String(take),
|
||||
days: String(recentDays),
|
||||
})
|
||||
if (recentStage !== 'all') {
|
||||
params.set('stage', recentStage)
|
||||
}
|
||||
const response = await authFetch(`${baseUrl}/requests/recent?${params.toString()}`)
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
throw new Error(`Recent requests failed: ${response.status}`)
|
||||
}
|
||||
const data = await response.json()
|
||||
if (Array.isArray(data?.results)) {
|
||||
setRecent(normalizeRecentResults(data.results))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
setRecentError('Recent requests are not available right now.')
|
||||
} finally {
|
||||
setRecentLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
load()
|
||||
}, [recentDays, recentStage])
|
||||
|
||||
useEffect(() => {
|
||||
if (!authReady) {
|
||||
return
|
||||
}
|
||||
const load = async () => {
|
||||
setServicesLoading(true)
|
||||
setServicesError(null)
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const response = await authFetch(`${baseUrl}/status/services`)
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
throw new Error(`Service status failed: ${response.status}`)
|
||||
}
|
||||
const data = await response.json()
|
||||
setServicesStatus(data)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
setServicesError('Service status is not available right now.')
|
||||
} finally {
|
||||
setServicesLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
if (liveStreamConnected) {
|
||||
return
|
||||
}
|
||||
const timer = setInterval(load, 30000)
|
||||
return () => clearInterval(timer)
|
||||
}, [authReady, liveStreamConnected, router])
|
||||
|
||||
useEffect(() => {
|
||||
if (!authReady) {
|
||||
setLiveStreamConnected(false)
|
||||
return
|
||||
}
|
||||
if (!getToken()) {
|
||||
setLiveStreamConnected(false)
|
||||
return
|
||||
}
|
||||
const baseUrl = getApiBase()
|
||||
let closed = false
|
||||
let source: EventSource | null = null
|
||||
|
||||
const connect = async () => {
|
||||
try {
|
||||
const streamToken = await getEventStreamToken()
|
||||
if (closed) return
|
||||
const params = new URLSearchParams({
|
||||
stream_token: streamToken,
|
||||
recent_days: String(recentDays),
|
||||
})
|
||||
if (recentStage !== 'all') {
|
||||
params.set('recent_stage', recentStage)
|
||||
}
|
||||
const streamUrl = `${baseUrl}/events/stream?${params.toString()}`
|
||||
source = new EventSource(streamUrl)
|
||||
|
||||
source.onopen = () => {
|
||||
if (closed) return
|
||||
setLiveStreamConnected(true)
|
||||
}
|
||||
|
||||
source.onmessage = (event) => {
|
||||
if (closed) return
|
||||
setLiveStreamConnected(true)
|
||||
try {
|
||||
const payload = JSON.parse(event.data)
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return
|
||||
}
|
||||
if (payload.type === 'home_recent') {
|
||||
if (Array.isArray(payload.results)) {
|
||||
setRecent(normalizeRecentResults(payload.results))
|
||||
setRecentError(null)
|
||||
setRecentLoading(false)
|
||||
} else if (typeof payload.error === 'string' && payload.error.trim()) {
|
||||
setRecentError('Recent requests are not available right now.')
|
||||
setRecentLoading(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (payload.type === 'home_services') {
|
||||
if (payload.status && typeof payload.status === 'object') {
|
||||
setServicesStatus(payload.status)
|
||||
setServicesError(null)
|
||||
setServicesLoading(false)
|
||||
} else if (typeof payload.error === 'string' && payload.error.trim()) {
|
||||
setServicesError('Service status is not available right now.')
|
||||
setServicesLoading(false)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
source.onerror = () => {
|
||||
if (closed) return
|
||||
setLiveStreamConnected(false)
|
||||
}
|
||||
} catch (error) {
|
||||
if (closed) return
|
||||
console.error(error)
|
||||
setLiveStreamConnected(false)
|
||||
}
|
||||
}
|
||||
|
||||
void connect()
|
||||
|
||||
return () => {
|
||||
closed = true
|
||||
setLiveStreamConnected(false)
|
||||
source?.close()
|
||||
}
|
||||
}, [authReady, recentDays, recentStage])
|
||||
|
||||
const runSearch = async (term: string) => {
|
||||
try {
|
||||
const baseUrl = getApiBase()
|
||||
const response = await authFetch(`${baseUrl}/requests/search?query=${encodeURIComponent(term)}`)
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
clearToken()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
throw new Error(`Search failed: ${response.status}`)
|
||||
}
|
||||
const data = await response.json()
|
||||
if (Array.isArray(data?.results)) {
|
||||
setSearchResults(
|
||||
data.results.map((item: any) => ({
|
||||
title: item.title,
|
||||
year: item.year,
|
||||
type: item.type,
|
||||
requestId: item.requestId,
|
||||
statusLabel: item.statusLabel,
|
||||
requestedBy: item.requestedBy ?? null,
|
||||
accessible: Boolean(item.accessible),
|
||||
}))
|
||||
)
|
||||
setSearchError(null)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
setSearchError('Search failed. Try a request ID instead.')
|
||||
setSearchResults([])
|
||||
}
|
||||
}
|
||||
|
||||
const resolveArtworkUrl = (url?: string | null) => {
|
||||
if (!url) return null
|
||||
return url.startsWith('http') ? url : `${getApiBase()}${url}`
|
||||
}
|
||||
|
||||
const formatRequestTime = (value?: string | null) => {
|
||||
if (!value) return null
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.valueOf())) return value
|
||||
return date.toLocaleString()
|
||||
}
|
||||
|
||||
const serviceItems = servicesStatus?.services ?? []
|
||||
const serviceUpCount = serviceItems.filter((service) => service.status === 'up').length
|
||||
const serviceAttentionCount = serviceItems.filter((service) =>
|
||||
['down', 'degraded', 'not_configured'].includes(service.status)
|
||||
).length
|
||||
const serviceOverall = servicesStatus?.overall ?? 'unknown'
|
||||
const serviceStatusLabel = servicesLoading
|
||||
? 'Checking services...'
|
||||
: servicesError
|
||||
? 'Status not available yet'
|
||||
: serviceOverall === 'up'
|
||||
? 'Services are up and running'
|
||||
: serviceOverall === 'down'
|
||||
? 'Something is down'
|
||||
: 'Some services need attention'
|
||||
const serviceSummary = servicesError
|
||||
? 'Unable to load service status'
|
||||
: serviceItems.length === 0
|
||||
? 'No services reported yet'
|
||||
: serviceAttentionCount > 0
|
||||
? `${serviceAttentionCount} of ${serviceItems.length} need attention`
|
||||
: `${serviceUpCount} of ${serviceItems.length} online`
|
||||
const orderedServices = ['Seerr', 'Sonarr', 'Radarr', 'Prowlarr', 'qBittorrent', 'Jellyfin'].map(
|
||||
(name) => {
|
||||
const item = serviceItems.find((entry) => entry.name === name)
|
||||
return { name, status: item?.status ?? 'unknown', message: item?.message }
|
||||
}
|
||||
)
|
||||
const activeRecentCount = recent.filter((item) => {
|
||||
const label = String(item.statusLabel ?? '').toLowerCase()
|
||||
return !label.includes('ready') && !label.includes('available') && !label.includes('declined')
|
||||
}).length
|
||||
|
||||
return (
|
||||
<main className="card">
|
||||
<section className="ops-metric-grid">
|
||||
<div className="ops-metric-card">
|
||||
<span className="section-kicker">Service mesh</span>
|
||||
<strong>
|
||||
{serviceUpCount}/{serviceItems.length || 0}
|
||||
</strong>
|
||||
<p>{servicesLoading ? 'Checking services now.' : 'Configured services online.'}</p>
|
||||
</div>
|
||||
<div className="ops-metric-card">
|
||||
<span className="section-kicker">Attention</span>
|
||||
<strong>{serviceAttentionCount}</strong>
|
||||
<p>Services reporting down, degraded, or not configured.</p>
|
||||
</div>
|
||||
<div className="ops-metric-card">
|
||||
<span className="section-kicker">Loaded requests</span>
|
||||
<strong>{recent.length}</strong>
|
||||
<p>Returned by the live request cache.</p>
|
||||
</div>
|
||||
<div className="ops-metric-card">
|
||||
<span className="section-kicker">Active queue</span>
|
||||
<strong>{activeRecentCount}</strong>
|
||||
<p>Loaded requests still moving through the pipeline.</p>
|
||||
</div>
|
||||
</section>
|
||||
<div className="layout-grid">
|
||||
<section className="recent centerpiece">
|
||||
<details className="system-status system-status-dropdown">
|
||||
<summary className="system-summary">
|
||||
<span className="system-summary-copy">
|
||||
<span className="section-kicker">System status</span>
|
||||
<strong>{serviceSummary}</strong>
|
||||
<span>{serviceStatusLabel}</span>
|
||||
</span>
|
||||
<span className="system-summary-actions">
|
||||
<span className={`system-pill system-pill-${serviceOverall}`}>
|
||||
{servicesLoading ? 'Checking' : serviceOverall.replaceAll('_', ' ')}
|
||||
</span>
|
||||
<span className="system-dropdown-cue" aria-hidden="true">Open</span>
|
||||
</span>
|
||||
</summary>
|
||||
<div className="system-list">
|
||||
{orderedServices.map(({ name, status, message }) => {
|
||||
const testing = serviceTesting[name] ?? false
|
||||
return (
|
||||
<div key={name} className={`system-item system-${status}`}>
|
||||
<span className="system-dot" />
|
||||
<div className="system-meta">
|
||||
<span className="system-name">{name}</span>
|
||||
<span className="system-test-message">
|
||||
{serviceTestResults[name] ?? message ?? 'No recent detail'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="system-actions">
|
||||
<span className="system-state">
|
||||
{status === 'up'
|
||||
? 'Up'
|
||||
: status === 'down'
|
||||
? 'Down'
|
||||
: status === 'degraded'
|
||||
? 'Needs attention'
|
||||
: status === 'not_configured'
|
||||
? 'Not configured'
|
||||
: 'Unknown'}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="system-test"
|
||||
onClick={() => void testService(name)}
|
||||
disabled={testing}
|
||||
>
|
||||
{testing ? 'Testing...' : 'Test'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</details>
|
||||
<div className="recent-header">
|
||||
<h2>{role === 'admin' ? 'All requests' : 'My recent requests'}</h2>
|
||||
{authReady && (
|
||||
<div className="recent-filter-group">
|
||||
<label className="recent-filter">
|
||||
<span>Show</span>
|
||||
<select
|
||||
value={recentDays}
|
||||
onChange={(event) => setRecentDays(Number(event.target.value))}
|
||||
>
|
||||
<option value={0}>All</option>
|
||||
<option value={30}>30 days</option>
|
||||
<option value={60}>60 days</option>
|
||||
<option value={90}>90 days</option>
|
||||
<option value={180}>180 days</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="recent-filter">
|
||||
<span>Stage</span>
|
||||
<select
|
||||
value={recentStage}
|
||||
onChange={(event) => setRecentStage(event.target.value)}
|
||||
>
|
||||
{REQUEST_STAGE_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="recent-grid">
|
||||
{recentLoading ? (
|
||||
<div className="loading-center">
|
||||
<div className="spinner" aria-hidden="true" />
|
||||
<span className="loading-text">Loading recent requests…</span>
|
||||
</div>
|
||||
) : recentError ? (
|
||||
<button type="button" disabled>
|
||||
{recentError}
|
||||
</button>
|
||||
) : recent.length === 0 ? (
|
||||
<button type="button" disabled>
|
||||
No recent requests found
|
||||
</button>
|
||||
) : (
|
||||
recent.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => router.push(`/requests/${item.id}`)}
|
||||
className="recent-card"
|
||||
>
|
||||
{item.artwork?.poster_url && (
|
||||
<img
|
||||
className="recent-poster"
|
||||
src={resolveArtworkUrl(item.artwork.poster_url) ?? ''}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
/>
|
||||
)}
|
||||
<span className="recent-info">
|
||||
<span className="recent-title">
|
||||
{item.title || 'Untitled'}
|
||||
{item.year ? ` (${item.year})` : ''}
|
||||
</span>
|
||||
<span className="recent-meta">
|
||||
{item.statusLabel ? item.statusLabel : 'Status not available yet'} · Request{' '}
|
||||
{item.id}
|
||||
{item.createdAt ? ` · ${formatRequestTime(item.createdAt)}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<aside className="side-panel">
|
||||
<section className="main-panel find-panel">
|
||||
<div className="find-header">
|
||||
<h1>Search all requests</h1>
|
||||
<p className="lede">
|
||||
Search any request by title + year or request number and see whether it already
|
||||
exists in the system.
|
||||
</p>
|
||||
</div>
|
||||
<div className="find-controls">
|
||||
<form onSubmit={submit} className="search search-row">
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="e.g. Dune 2021 or 1289"
|
||||
/>
|
||||
<button type="submit">Check status</button>
|
||||
</form>
|
||||
<div className="filters filters-compact">
|
||||
<div className="filter">
|
||||
<span>Type</span>
|
||||
<div className="pill-group">
|
||||
<button type="button">TV</button>
|
||||
<button type="button">Movie</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="filter">
|
||||
<span>Status</span>
|
||||
<div className="pill-group">
|
||||
<button type="button">Pending</button>
|
||||
<button type="button">Approved</button>
|
||||
<button type="button">Processing</button>
|
||||
<button type="button">Failed</button>
|
||||
<button type="button">Available</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<section className="recent results-panel">
|
||||
<h2>Search results</h2>
|
||||
<div className="recent-grid">
|
||||
{searchError ? (
|
||||
<button type="button" disabled>
|
||||
{searchError}
|
||||
</button>
|
||||
) : searchResults.length === 0 ? (
|
||||
<button type="button" disabled>
|
||||
No matches yet
|
||||
</button>
|
||||
) : (
|
||||
searchResults.map((item, index) => (
|
||||
<button
|
||||
key={`${item.title || 'Untitled'}-${index}`}
|
||||
type="button"
|
||||
disabled={!item.requestId}
|
||||
onClick={() =>
|
||||
item.requestId && router.push(`/requests/${item.requestId}`)
|
||||
}
|
||||
>
|
||||
{item.title || 'Untitled'} {item.year ? `(${item.year})` : ''}{' '}
|
||||
{!item.requestId
|
||||
? '- not requested'
|
||||
: item.statusLabel
|
||||
? `- ${item.statusLabel}`
|
||||
: '- already requested'}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user