Spaces:
Runtime error
Runtime error
File size: 23,153 Bytes
c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 49f22ac c5cf697 | 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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { deleteUserAdmin, getKbStatus, listUsersAdmin, mergeKbCsvUpload } from '../api/admin'
import { clearAdminSession, getStoredAdmin } from '../auth/adminStorage'
import ComsatsLogo from '../components/ComsatsLogo'
const PAGE_SIZE = 15
function initialsFromProfile(fullName, email) {
const n = (fullName || '').trim()
if (n) {
const parts = n.split(/\s+/).filter(Boolean)
if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
return n.slice(0, 2).toUpperCase()
}
const local = (email || '').split('@')[0] || '?'
return local.slice(0, 2).toUpperCase()
}
function shortUserId(id) {
if (!id) return '—'
if (id.length <= 14) return id
return `${id.slice(0, 8)}…${id.slice(-4)}`
}
export default function AdminPanel() {
const navigate = useNavigate()
const [admin] = useState(() => getStoredAdmin())
const [section, setSection] = useState('kb')
const [page, setPage] = useState(1)
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [usersError, setUsersError] = useState('')
const [deletingId, setDeletingId] = useState(null)
const [copiedId, setCopiedId] = useState(null)
const [kbStatus, setKbStatus] = useState(null)
const [kbLoading, setKbLoading] = useState(true)
const [kbFile, setKbFile] = useState(null)
const [kbUploading, setKbUploading] = useState(false)
const [kbError, setKbError] = useState('')
const [kbSuccess, setKbSuccess] = useState('')
const loadKb = useCallback(async () => {
setKbError('')
setKbLoading(true)
try {
setKbStatus(await getKbStatus())
} catch (e) {
setKbError(e.message || 'Failed to load knowledge base status')
setKbStatus(null)
} finally {
setKbLoading(false)
}
}, [])
useEffect(() => {
loadKb()
}, [loadKb])
const loadUsers = useCallback(async () => {
setUsersError('')
setLoading(true)
try {
const res = await listUsersAdmin(page, PAGE_SIZE)
setData(res)
} catch (e) {
setUsersError(e.message || 'Failed to load users')
setData(null)
} finally {
setLoading(false)
}
}, [page])
useEffect(() => {
loadUsers()
}, [loadUsers])
function logout() {
clearAdminSession()
navigate('/admin/login', { replace: true })
}
async function copyUserId(userId) {
try {
await navigator.clipboard.writeText(userId)
setCopiedId(userId)
window.setTimeout(() => setCopiedId(null), 2000)
} catch {
setCopiedId(null)
}
}
async function onDelete(userId, email) {
if (!window.confirm(`Remove ${email} from the directory? All of their conversations will be permanently deleted.`))
return
setDeletingId(userId)
setUsersError('')
try {
await deleteUserAdmin(userId)
await loadUsers()
} catch (e) {
setUsersError(e.message || 'Delete failed')
} finally {
setDeletingId(null)
}
}
const pages = data?.pages ?? 0
const total = data?.total ?? 0
async function onKbMergeUpload(e) {
e.preventDefault()
if (!kbFile) return
setKbError('')
setKbSuccess('')
setKbUploading(true)
const fileRef = kbFile
try {
const res = await mergeKbCsvUpload(() => {
const fd = new FormData()
fd.append('file', fileRef)
return fd
})
setKbSuccess(
`${res.message} Added ${res.rows_merged ?? 0} rows to the index. File stored as ${res.saved_as ?? 'upload'}.`,
)
setKbFile(null)
const input = document.getElementById('admin-kb-merge-csv')
if (input) input.value = ''
await loadKb()
} catch (err) {
setKbError(err.message || 'Upload failed')
} finally {
setKbUploading(false)
}
}
const tabBtn =
'rounded-lg px-4 py-2 text-[13px] font-semibold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-purple focus-visible:ring-offset-2'
const tabActive = 'bg-white text-comsats-purple shadow-sm ring-1 ring-slate-200/90'
const tabIdle = 'text-slate-600 hover:bg-white/60 hover:text-slate-900'
return (
<div className="flex min-h-dvh flex-col bg-[#f4f6fa]">
<header className="sticky top-0 z-20 border-b border-slate-200/80 bg-white/95 backdrop-blur-md">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-4 px-4 py-3.5 sm:px-8">
<div className="flex min-w-0 items-center gap-3">
<div className="rounded-xl bg-white p-1 shadow-sm ring-1 ring-slate-200/80">
<ComsatsLogo className="h-10 w-10" />
</div>
<div className="min-w-0">
<p className="text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500">CUI Connect</p>
<h1 className="truncate text-lg font-bold tracking-tight text-slate-900">Administration</h1>
<p className="truncate text-[12px] text-slate-500">{admin?.email ?? 'Signed in'}</p>
</div>
</div>
<button
type="button"
onClick={logout}
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-[13px] font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50"
>
Sign out
</button>
</div>
</header>
<div className="mx-auto w-full max-w-6xl flex-1 px-4 py-6 sm:px-8 sm:py-8">
<nav className="mb-8 flex flex-wrap gap-2 rounded-xl bg-slate-200/40 p-1.5 ring-1 ring-slate-200/60 sm:inline-flex">
<button
type="button"
role="tab"
aria-selected={section === 'kb'}
className={`${tabBtn} ${section === 'kb' ? tabActive : tabIdle}`}
onClick={() => setSection('kb')}
>
Knowledge base
</button>
<button
type="button"
role="tab"
aria-selected={section === 'users'}
className={`${tabBtn} ${section === 'users' ? tabActive : tabIdle}`}
onClick={() => setSection('users')}
>
Users
</button>
</nav>
{section === 'kb' ? (
<div className="space-y-8">
<div>
<h2 className="text-xl font-bold tracking-tight text-slate-900">Knowledge base</h2>
<p className="mt-1 max-w-2xl text-[15px] leading-relaxed text-slate-600">
Update the assistant's retrieval index by uploading FAQ-style CSV data. Each upload is embedded and
merged into the live FAISS index without a full rebuild.
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-2xl border border-slate-200/90 bg-white p-5 shadow-sm ring-1 ring-slate-900/[0.02]">
<p className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Retriever</p>
<p className="mt-2 text-lg font-semibold text-slate-900">
{kbLoading ? '…' : kbStatus?.retriever_ready ? 'Operational' : 'Unavailable'}
</p>
<p className="mt-1 text-[12px] text-slate-500">
{kbLoading ? 'Checking status' : kbStatus?.retriever_ready ? 'Ready for queries' : 'Check server logs'}
</p>
</div>
<div className="rounded-2xl border border-slate-200/90 bg-white p-5 shadow-sm ring-1 ring-slate-900/[0.02]">
<p className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Vectors</p>
<p className="mt-2 text-lg font-semibold text-slate-900">
{kbLoading ? '…' : kbStatus?.vector_count != null ? kbStatus.vector_count.toLocaleString() : '—'}
</p>
<p className="mt-1 text-[12px] text-slate-500">Documents in FAISS index</p>
</div>
<div className="rounded-2xl border border-slate-200/90 bg-white p-5 shadow-sm ring-1 ring-slate-900/[0.02]">
<p className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Upload history</p>
<p className="mt-2 text-lg font-semibold text-slate-900">
{kbLoading ? '…' : (kbStatus?.uploaded_csv_count ?? kbStatus?.uploaded_csv_files?.length ?? 0)}
</p>
<p className="mt-1 text-[12px] text-slate-500">CSV files on disk</p>
</div>
<div className="rounded-2xl border border-slate-200/90 bg-white p-5 shadow-sm ring-1 ring-slate-900/[0.02]">
<p className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Index bundle</p>
<p className="mt-2 text-lg font-semibold text-slate-900">
{kbLoading ? '…' : kbStatus?.index_on_disk ? 'Present' : 'Missing'}
</p>
<p className="mt-1 text-[12px] text-slate-500">Saved under configured path</p>
</div>
</div>
<div className="overflow-hidden rounded-2xl border border-slate-200/90 bg-white shadow-[0_16px_48px_-28px_rgba(15,23,42,0.25)] ring-1 ring-slate-900/[0.03]">
<div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-6 py-5 sm:px-8">
<h3 className="text-base font-semibold text-slate-900">Merge new content</h3>
<ol className="mt-3 list-decimal space-y-1.5 pl-5 text-[13px] text-slate-600">
<li>Prepare a UTF-8 CSV in the same column layout as your existing FAQ knowledge.</li>
<li>Select the file below — only <span className="font-medium text-slate-800">.csv</span> up to 25 MB.</li>
<li>Confirm merge; rows are embedded and appended via <code className="rounded bg-slate-100 px-1 text-[12px]">merge_from</code>.</li>
</ol>
</div>
<div className="px-6 py-6 sm:px-8 sm:py-8">
{kbError ? (
<div
role="alert"
className="mb-5 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800"
>
{kbError}
</div>
) : null}
{kbSuccess ? (
<div
role="status"
className="mb-5 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-900"
>
{kbSuccess}
</div>
) : null}
<form onSubmit={onKbMergeUpload} className="flex flex-col gap-6 lg:flex-row lg:items-end">
<div className="min-w-0 flex-1">
<label htmlFor="admin-kb-merge-csv" className="mb-2 block text-sm font-medium text-slate-700">
CSV file
</label>
<div className="rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50/50 px-5 py-8 text-center transition-colors hover:border-comsats-purple/25 hover:bg-slate-50">
<input
id="admin-kb-merge-csv"
name="file"
type="file"
accept=".csv,text/csv"
disabled={kbUploading}
onChange={(ev) => setKbFile(ev.target.files?.[0] ?? null)}
className="mx-auto block max-w-full cursor-pointer text-[13px] text-slate-800 file:mr-4 file:cursor-pointer file:rounded-xl file:border-0 file:bg-comsats-purple file:px-4 file:py-2.5 file:text-[13px] file:font-semibold file:text-white file:shadow-sm hover:file:brightness-110"
/>
<p className="mt-3 text-[12px] text-slate-500">
{kbFile ? (
<span className="font-medium text-slate-700">{kbFile.name}</span>
) : (
'Choose a file or drag into the file picker (browser dependent)'
)}
</p>
</div>
</div>
<button
type="submit"
disabled={!kbFile || kbUploading}
className="h-[52px] shrink-0 rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-8 text-sm font-semibold text-white shadow-lg shadow-comsats-purple/20 transition-all hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-50 lg:self-auto"
>
{kbUploading ? 'Merging…' : 'Upload & merge'}
</button>
</form>
{kbStatus && !kbLoading ? (
<details className="mt-8 rounded-xl border border-slate-100 bg-slate-50/80 px-4 py-3 text-[13px] text-slate-600">
<summary className="cursor-pointer select-none font-semibold text-slate-800">Technical paths & files</summary>
<dl className="mt-4 grid gap-3 sm:grid-cols-2">
<div>
<dt className="text-[11px] font-bold uppercase tracking-wide text-slate-500">FAISS directory</dt>
<dd className="mt-1 break-all font-mono text-[12px] text-slate-800">{kbStatus.index_path}</dd>
</div>
<div>
<dt className="text-[11px] font-bold uppercase tracking-wide text-slate-500">Upload directory</dt>
<dd className="mt-1 break-all font-mono text-[12px] text-slate-800">{kbStatus.kb_upload_dir}</dd>
</div>
<div className="sm:col-span-2">
<dt className="text-[11px] font-bold uppercase tracking-wide text-slate-500">Bundled base CSVs</dt>
<dd className="mt-1 text-slate-800">
{kbStatus.base_csv_files?.length ? kbStatus.base_csv_files.join(', ') : 'None detected'}
</dd>
</div>
<div className="sm:col-span-2">
<dt className="text-[11px] font-bold uppercase tracking-wide text-slate-500">Uploaded CSV filenames</dt>
<dd className="mt-1 max-h-28 overflow-y-auto text-slate-800">
{kbStatus.uploaded_csv_files?.length
? kbStatus.uploaded_csv_files.join(', ')
: 'None yet'}
</dd>
</div>
</dl>
</details>
) : kbLoading ? (
<p className="mt-6 text-sm text-slate-500">Loading knowledge base status…</p>
) : null}
</div>
</div>
</div>
) : (
<div className="space-y-6">
<div className="flex flex-wrap items-end justify-between gap-4">
<div>
<h2 className="text-xl font-bold tracking-tight text-slate-900">Registered users</h2>
<p className="mt-1 text-[15px] text-slate-600">
{total.toLocaleString()} {total === 1 ? 'account' : 'accounts'}
{pages > 1 ? ` · Page ${page} of ${pages}` : ''}
</p>
</div>
</div>
{usersError ? (
<div
role="alert"
className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800"
>
{usersError}
</div>
) : null}
<div className="overflow-hidden rounded-2xl border border-slate-200/90 bg-white shadow-sm ring-1 ring-slate-900/[0.03]">
<div className="overflow-x-auto">
<table className="w-full min-w-[720px] table-fixed border-collapse text-left">
<thead>
<tr className="border-b border-slate-200 bg-slate-50/95">
<th className="w-12 px-4 py-3.5 text-[11px] font-bold uppercase tracking-wider text-slate-500 sm:px-5">
#
</th>
<th className="px-4 py-3.5 text-[11px] font-bold uppercase tracking-wider text-slate-500 sm:px-5">
Member
</th>
<th className="hidden w-[200px] px-4 py-3.5 text-[11px] font-bold uppercase tracking-wider text-slate-500 md:table-cell sm:px-5">
User ID
</th>
<th className="w-[120px] px-4 py-3.5 text-[11px] font-bold uppercase tracking-wider text-slate-500 sm:px-5">
Chats
</th>
<th className="w-[130px] px-4 py-3.5 text-right text-[11px] font-bold uppercase tracking-wider text-slate-500 sm:px-5">
Actions
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{loading ? (
<tr>
<td colSpan={5} className="px-5 py-16 text-center">
<div className="inline-flex items-center gap-3 text-slate-500">
<span className="h-5 w-5 animate-spin rounded-full border-2 border-comsats-purple/20 border-t-comsats-purple" />
<span className="text-[14px] font-medium">Loading directory…</span>
</div>
</td>
</tr>
) : !data?.items?.length ? (
<tr>
<td colSpan={5} className="px-5 py-16 text-center text-[14px] text-slate-500">
No registered users yet.
</td>
</tr>
) : (
data.items.map((row, idx) => (
<tr key={row.user_id} className="bg-white transition-colors hover:bg-slate-50/90">
<td className="px-4 py-4 tabular-nums text-[13px] text-slate-400 sm:px-5">
{(page - 1) * PAGE_SIZE + idx + 1}
</td>
<td className="px-4 py-4 sm:px-5">
<div className="flex items-center gap-3">
<div
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-comsats-purple/15 to-comsats-blue/20 text-[13px] font-bold text-comsats-purple ring-2 ring-white shadow-sm"
aria-hidden
>
{initialsFromProfile(row.full_name, row.email)}
</div>
<div className="min-w-0">
<p className="truncate text-[14px] font-semibold text-slate-900">
{row.full_name?.trim() || '—'}
</p>
<p className="truncate text-[13px] text-slate-500">{row.email}</p>
</div>
</div>
</td>
<td className="hidden px-4 py-4 md:table-cell sm:px-5">
<div className="flex items-center gap-2">
<code
className="block max-w-[160px] truncate rounded-lg bg-slate-100 px-2 py-1 font-mono text-[11px] text-slate-700"
title={row.user_id}
>
{shortUserId(row.user_id)}
</code>
<button
type="button"
onClick={() => copyUserId(row.user_id)}
className="shrink-0 rounded-lg border border-slate-200 bg-white px-2 py-1 text-[11px] font-semibold text-slate-600 hover:bg-slate-50"
>
{copiedId === row.user_id ? 'Copied' : 'Copy'}
</button>
</div>
</td>
<td className="px-4 py-4 sm:px-5">
<span className="inline-flex rounded-full bg-slate-100 px-2.5 py-0.5 text-[12px] font-semibold tabular-nums text-slate-700">
{(row.chat_count ?? 0).toLocaleString()}
</span>
</td>
<td className="px-4 py-4 text-right sm:px-5">
<button
type="button"
disabled={deletingId === row.user_id}
onClick={() => onDelete(row.user_id, row.email)}
className="rounded-lg border border-red-200/90 bg-white px-3 py-1.5 text-[12px] font-semibold text-red-700 shadow-sm transition-colors hover:bg-red-50 disabled:opacity-50"
>
{deletingId === row.user_id ? 'Removing…' : 'Remove'}
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{pages > 1 ? (
<nav className="flex flex-wrap items-center justify-between gap-3" aria-label="Pagination">
<button
type="button"
disabled={page <= 1 || loading}
onClick={() => setPage((p) => Math.max(1, p - 1))}
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-[13px] font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40"
>
Previous
</button>
<span className="text-[13px] font-medium text-slate-500">
Page {page} / {pages}
</span>
<button
type="button"
disabled={page >= pages || loading}
onClick={() => setPage((p) => Math.min(pages, p + 1))}
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-[13px] font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40"
>
Next
</button>
</nav>
) : null}
</div>
)}
</div>
</div>
)
}
|