-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_app.admin.index.tsx
More file actions
245 lines (244 loc) · 7.29 KB
/
Copy path_app.admin.index.tsx
File metadata and controls
245 lines (244 loc) · 7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import {
Button,
Card,
EmptyState,
Grid,
Selector,
Stack,
Table,
TextInput,
} from '@astryxdesign/core'
import { useQuery } from '@tanstack/react-query'
import { createFileRoute, redirect } from '@tanstack/react-router'
import {
createColumnHelper,
createSortedRowModel,
rowSortingFeature,
tableFeatures,
useTable,
} from '@tanstack/react-table'
import { useMemo, useState } from 'react'
import { StatusBadge } from '../components/job-view'
import { jobsApi } from '../lib/api'
import { authClient, getSession, isAdmin } from '../lib/auth'
import { jobKeys, queryClient } from '../lib/query'
import { ApiError } from '../lib/types'
import type { Job, JobStatus } from '../lib/types'
export const Route = createFileRoute('/_app/admin/')({
beforeLoad: async () => {
if (!isAdmin(await getSession())) throw redirect({ to: '/jobs' })
},
component: AdminPage,
})
const pageSize = 100
const features = tableFeatures({
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
})
const helper = createColumnHelper<typeof features, Job>()
const columns = helper.columns([
helper.accessor('id', { header: 'Job ID' }),
helper.accessor('userId', { header: 'Owner' }),
helper.accessor('status', {
header: 'Status',
cell: (info) => <StatusBadge status={info.getValue()} />,
}),
helper.accessor('totalStages', { header: 'Stages' }),
helper.accessor('totalTime', { header: 'Time (ms)' }),
helper.accessor('failStage', {
header: 'Fail stage',
cell: (info) => info.getValue() ?? '—',
}),
helper.accessor('createdAt', {
header: 'Created',
cell: (info) => new Date(info.getValue()).toLocaleString(),
}),
])
function AdminPage() {
const [status, setStatus] = useState<JobStatus | ''>('')
const [owner, setOwner] = useState('')
const [page, setPage] = useState(1)
const query = useQuery({
queryKey: [...jobKeys.admin(), page],
queryFn: () => jobsApi.all(page, pageSize),
retry: false,
refetchInterval: ({ state }) =>
state.data?.jobs.some(
(job) => job.status === 'PENDING' || job.status === 'ACTIVE',
)
? 5_000
: false,
})
const data = useMemo(
() =>
(query.data?.jobs ?? []).filter(
(job) =>
(!status || job.status === status) &&
(!owner || job.userId.toLowerCase().includes(owner.toLowerCase())),
),
[query.data, status, owner],
)
const table = useTable({
features,
data,
columns,
})
const statusCounts = query.data?.total
const totalJobs = Object.values(statusCounts ?? {}).reduce(
(sum, count) => sum + count,
0,
)
if (query.error instanceof ApiError && query.error.kind === 'forbidden') {
queryClient.removeQueries({ queryKey: jobKeys.admin() })
void authClient.getSession()
return (
<EmptyState
title="Administrator access denied"
description="The server refused this request. Your role may have changed; sign in again if this persists."
/>
)
}
if (query.isPending)
return (
<EmptyState
title="Loading all jobs"
description="Retrieving the administrator job collection…"
/>
)
if (query.isError)
return (
<EmptyState
title="All jobs could not be loaded"
description={query.error.message}
actions={<Button label="Retry" onClick={() => void query.refetch()} />}
/>
)
return (
<Stack gap={5}>
<div className="page-heading">
<div>
<div className="eyebrow">Administration</div>
<h1>All jobs</h1>
<p>
Inspect jobs across all owners. Backend authorization remains
authoritative.
</p>
</div>
</div>
<Card className="form-panel">
<Grid
columns={{ minWidth: 280, max: 3, repeat: 'fit' }}
rowGap={3}
columnGap={3}
align="end"
>
<Selector
label="Status"
options={['', 'PENDING', 'ACTIVE', 'COMPLETED', 'FAILED']}
value={status}
onChange={(value) => setStatus(value as JobStatus | '')}
placeholder="All statuses"
/>
<TextInput
label="Owner ID"
value={owner}
onChange={setOwner}
placeholder="Filter by owner"
/>
<Button
label="Clear filters"
variant="secondary"
onClick={() => {
setStatus('')
setOwner('')
}}
/>
</Grid>
</Card>
<div className="metrics-grid" aria-label="All job statistics">
<div className="metric-card">
<span className="metric-label">Total jobs</span>
<h2>{totalJobs}</h2>
</div>
{(
[
['PENDING', 'Pending'],
['ACTIVE', 'Active'],
['COMPLETED', 'Completed'],
['FAILED', 'Failed'],
] as const
).map(([status, label]) => (
<div key={status} className="metric-card">
<span className="metric-label">{label}</span>
<h2>{statusCounts?.[status] ?? 0}</h2>
</div>
))}
</div>
{query.data.jobs.length === 0 ? (
<EmptyState
title="No jobs exist"
description="The administrator collection is empty."
/>
) : data.length === 0 ? (
<EmptyState
title="No matching jobs"
description="Clear or change the active filters."
/>
) : (
<div className="data-panel">
<Table>
<thead>
{table.getHeaderGroups().map((group) => (
<tr key={group.id}>
{group.headers.map((header) => (
<th key={header.id}>
<button onClick={header.column.getToggleSortingHandler()}>
<table.FlexRender header={header} />
<span aria-hidden="true">
{header.column.getIsSorted() === 'asc'
? ' ↑'
: header.column.getIsSorted() === 'desc'
? ' ↓'
: ''}
</span>
</button>
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getAllCells().map((cell) => (
<td
key={cell.id}
data-label={String(cell.column.columnDef.header)}
>
<table.FlexRender cell={cell} />
</td>
))}
</tr>
))}
</tbody>
</Table>
</div>
)}
<div className="filter-bar">
<span>Page {page}</span>
<Button
label="Previous"
variant="secondary"
onClick={() => setPage((current) => current - 1)}
isDisabled={page === 1 || query.isFetching}
/>
<Button
label="Next"
variant="secondary"
onClick={() => setPage((current) => current + 1)}
isDisabled={page * pageSize >= totalJobs || query.isFetching}
/>
</div>
</Stack>
)
}