Spaces:
Sleeping
Sleeping
File size: 32,685 Bytes
345b8ff adf80ee 4dc66a3 adf80ee 4dc66a3 345b8ff dc11950 345b8ff 4dc66a3 0122657 4dc66a3 0122657 345b8ff a477044 adf80ee a477044 345b8ff 0122657 345b8ff 0122657 345b8ff 0122657 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff 0122657 345b8ff a477044 345b8ff adf80ee a477044 345b8ff a477044 0122657 a477044 0122657 a477044 adf80ee a477044 0122657 a477044 0122657 a477044 adf80ee a477044 adf80ee 345b8ff 0122657 345b8ff 0e8c152 4dc66a3 345b8ff 4dc66a3 a477044 4dc66a3 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff a477044 345b8ff adf80ee 345b8ff 4dc66a3 |
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 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 |
"use client";
import React, { useCallback, useMemo, useState, useRef, useEffect } from "react";
import Link from "next/link";
import { AdminRulesPanel } from "@/components/admin-rules-panel";
import { RuleExplanation } from "@/components/rule-explanation";
import { Footer } from "@/components/footer";
import { useTenant } from "@/contexts/TenantContext";
import { TenantSelector } from "@/components/tenant-selector";
import { canManageRules } from "@/lib/permissions";
const BACKEND_BASE_URL = process.env.NEXT_PUBLIC_BACKEND_BASE_URL ?? "http://localhost:8000";
type StatusState = { tone: "info" | "success" | "error"; message: string } | null;
const RBAC_ERROR_HINT =
"Insufficient permissions for this action. Switch your role to Admin or Owner in the navbar and try again.";
async function buildErrorMessage(response: Response) {
const fallback = `Backend error ${response.status}`;
try {
const text = await response.text();
if (!text) {
return response.status === 403 ? RBAC_ERROR_HINT : fallback;
}
try {
const parsed = JSON.parse(text);
const detail = parsed.detail || parsed.message;
if (response.status === 403) {
return detail || RBAC_ERROR_HINT;
}
return detail || fallback;
} catch {
if (response.status === 403) {
return text || RBAC_ERROR_HINT;
}
return text || fallback;
}
} catch {
return response.status === 403 ? RBAC_ERROR_HINT : fallback;
}
}
export default function AdminRulesPage() {
const { tenantId, role } = useTenant();
const [rulesInput, setRulesInput] = useState("");
const [deleteInput, setDeleteInput] = useState("");
const [rules, setRules] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<StatusState>(null);
const [isDragging, setIsDragging] = useState(false);
const [lastUpdated, setLastUpdated] = useState<string>("");
const [ruleExplanations, setRuleExplanations] = useState<Record<string, any>>({});
const [expandedRules, setExpandedRules] = useState<Set<string>>(new Set());
const [loadingExplanations, setLoadingExplanations] = useState<Set<string>>(new Set());
const fileInputRef = useRef<HTMLInputElement>(null);
// Set initial time only on client side to avoid hydration mismatch
useEffect(() => {
setLastUpdated(new Date().toLocaleTimeString());
}, []);
const headers = useMemo(() => {
if (!tenantId.trim()) return undefined;
return {
"Content-Type": "application/json",
"x-tenant-id": tenantId.trim(),
"x-user-role": role,
};
}, [tenantId, role]);
const requireTenant = useCallback(() => {
if (!tenantId.trim()) {
setStatus({ tone: "error", message: "Enter a tenant ID in the navbar first." });
return false;
}
return true;
}, [tenantId]);
const handleRefresh = useCallback(async () => {
if (!requireTenant()) return;
try {
setLoading(true);
setStatus({ tone: "info", message: "Loading rules..." });
const response = await fetch(`${BACKEND_BASE_URL}/admin/rules`, {
method: "GET",
headers,
});
if (!response.ok) {
throw new Error(await buildErrorMessage(response));
}
const data = await response.json();
setRules(data.rules ?? []);
setLastUpdated(new Date().toLocaleTimeString());
setStatus({ tone: "success", message: "Rules synced." });
} catch (error: any) {
setStatus({ tone: "error", message: error.message || "Failed to fetch rules" });
} finally {
setLoading(false);
}
}, [headers, requireTenant]);
const handleUpload = useCallback(async () => {
if (!requireTenant()) return;
const lines = rulesInput
.split("\n")
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#")); // Filter out comments and empty lines
if (!lines.length) {
setStatus({ tone: "error", message: "Add at least one rule to upload. (Comment lines starting with # are ignored)" });
return;
}
try {
setLoading(true);
setStatus({ tone: "info", message: `Uploading ${lines.length} rule(s)...` });
const response = await fetch(`${BACKEND_BASE_URL}/admin/rules/bulk?enhance=true`, {
method: "POST",
headers,
body: JSON.stringify({ rules: lines }),
});
if (!response.ok) {
throw new Error(await buildErrorMessage(response));
}
const data = await response.json();
await handleRefresh();
setRulesInput("");
// Store explanations for display and auto-expand
if (data.explanations && Array.isArray(data.explanations)) {
const explanationsMap: Record<string, any> = {};
const newExpanded = new Set(expandedRules);
data.explanations.forEach((exp: any) => {
if (exp.rule) {
explanationsMap[exp.rule] = exp;
// Auto-expand rules that have explanations
if (exp.explanation || exp.examples || exp.missing_patterns) {
newExpanded.add(exp.rule);
}
}
});
setRuleExplanations((prev) => ({ ...prev, ...explanationsMap }));
setExpandedRules(newExpanded);
}
const enhancedMsg = data.enhanced ? " (enhanced by LLM)" : "";
setStatus({ tone: "success", message: `Uploaded ${data.added_rules?.length || lines.length} rule(s)${enhancedMsg}.` });
} catch (error: any) {
setStatus({ tone: "error", message: error.message || "Failed to upload rules" });
} finally {
setLoading(false);
}
}, [handleRefresh, headers, requireTenant, rulesInput]);
const processFile = useCallback(async (file: File) => {
if (!requireTenant()) return;
const fileExt = file.name.split('.').pop()?.toLowerCase();
if (!fileExt || !['txt', 'pdf', 'doc', 'docx', 'md'].includes(fileExt)) {
setStatus({ tone: "error", message: "Unsupported file type. Supported: TXT, PDF, DOC, DOCX, MD" });
return;
}
try {
setLoading(true);
setStatus({ tone: "info", message: `Uploading and processing ${file.name}...` });
// For TXT files, read client-side for faster processing
if (fileExt === 'txt' || fileExt === 'md') {
const fileContent = await file.text();
const lines = fileContent
.split("\n")
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#"));
if (!lines.length) {
setStatus({ tone: "error", message: "No valid rules found in file (after filtering comments)." });
setLoading(false);
return;
}
// Upload rules via bulk endpoint
setStatus({ tone: "info", message: `Uploading ${lines.length} rule(s)...` });
const response = await fetch(`${BACKEND_BASE_URL}/admin/rules/bulk?enhance=true`, {
method: "POST",
headers,
body: JSON.stringify({ rules: lines }),
});
if (!response.ok) {
throw new Error(await buildErrorMessage(response));
}
const data = await response.json();
await handleRefresh();
// Store explanations for display and auto-expand
if (data.explanations && Array.isArray(data.explanations)) {
const explanationsMap: Record<string, any> = {};
const newExpanded = new Set(expandedRules);
data.explanations.forEach((exp: any) => {
if (exp.rule) {
explanationsMap[exp.rule] = exp;
// Auto-expand rules that have explanations
if (exp.explanation || exp.examples || exp.missing_patterns) {
newExpanded.add(exp.rule);
}
}
});
setRuleExplanations((prev) => ({ ...prev, ...explanationsMap }));
setExpandedRules(newExpanded);
}
const enhancedMsg = data.enhanced ? " (enhanced by LLM)" : "";
setStatus({ tone: "success", message: `Uploaded ${data.added_rules?.length || lines.length} rule(s) from ${file.name}${enhancedMsg}.` });
return;
}
// For PDF, DOC, DOCX - use backend file upload endpoint
const formData = new FormData();
formData.append('file', file);
setStatus({ tone: "info", message: `Extracting text from ${file.name}...` });
const response = await fetch(`${BACKEND_BASE_URL}/admin/rules/upload-file?enhance=true`, {
method: "POST",
headers: {
"x-tenant-id": tenantId.trim(),
"x-user-role": role,
},
body: formData,
});
if (!response.ok) {
throw new Error(await buildErrorMessage(response));
}
const data = await response.json();
await handleRefresh();
// Store explanations for display and auto-expand
if (data.explanations && Array.isArray(data.explanations)) {
const explanationsMap: Record<string, any> = {};
const newExpanded = new Set(expandedRules);
data.explanations.forEach((exp: any) => {
if (exp.rule) {
explanationsMap[exp.rule] = exp;
// Auto-expand rules that have explanations
if (exp.explanation || exp.examples || exp.missing_patterns) {
newExpanded.add(exp.rule);
}
}
});
setRuleExplanations((prev) => ({ ...prev, ...explanationsMap }));
setExpandedRules(newExpanded);
}
const enhancedMsg = data.enhanced ? " (enhanced by LLM)" : "";
setStatus({
tone: "success",
message: `Uploaded ${data.added_rules?.length || data.total_extracted || 0} rule(s) from ${file.name}${enhancedMsg}.`
});
} catch (error: any) {
setStatus({ tone: "error", message: error.message || "Failed to upload rules from file" });
} finally {
setLoading(false);
}
}, [handleRefresh, headers, requireTenant, tenantId]);
const handleFileUpload = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
await processFile(file);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}, [processFile]);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
}, []);
const handleDrop = useCallback(async (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
const file = e.dataTransfer.files?.[0];
if (!file) return;
const fileExt = file.name.split('.').pop()?.toLowerCase();
if (!fileExt || !['txt', 'pdf', 'doc', 'docx', 'md'].includes(fileExt)) {
setStatus({ tone: "error", message: "Unsupported file type. Supported: TXT, PDF, DOC, DOCX, MD" });
return;
}
await processFile(file);
}, [processFile]);
const fetchRuleExplanation = useCallback(async (rule: string) => {
if (!requireTenant()) return;
if (ruleExplanations[rule]) return; // Already have explanation
try {
setLoadingExplanations((prev) => new Set(prev).add(rule));
// Fetch explanation by calling the enhance endpoint
// We'll use POST with the rule in the body to get explanation
const response = await fetch(
`${BACKEND_BASE_URL}/admin/rules?enhance=true`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-tenant-id": tenantId.trim(),
"x-user-role": role,
},
body: JSON.stringify({ rule }),
}
);
if (response.ok) {
const data = await response.json();
if (data.explanation || data.examples || data.missing_patterns) {
setRuleExplanations((prev) => ({
...prev,
[rule]: {
explanation: data.explanation,
examples: data.examples || [],
missing_patterns: data.missing_patterns || [],
edge_cases: data.edge_cases || [],
improvements: data.improvements || [],
severity: data.severity,
},
}));
}
}
} catch (error) {
console.error("Failed to fetch rule explanation:", error);
} finally {
setLoadingExplanations((prev) => {
const next = new Set(prev);
next.delete(rule);
return next;
});
}
}, [tenantId, role, ruleExplanations, requireTenant]);
const toggleRuleExplanation = useCallback((rule: string) => {
setExpandedRules((prev) => {
const next = new Set(prev);
if (next.has(rule)) {
next.delete(rule);
} else {
next.add(rule);
// Fetch explanation if we don't have it
if (!ruleExplanations[rule]) {
fetchRuleExplanation(rule);
}
}
return next;
});
}, [ruleExplanations, fetchRuleExplanation]);
const handleDelete = useCallback(async () => {
if (!requireTenant()) return;
if (!deleteInput.trim()) {
setStatus({ tone: "error", message: "Enter the rule text you want to delete." });
return;
}
try {
setLoading(true);
setStatus({ tone: "info", message: "Deleting rule..." });
const response = await fetch(
`${BACKEND_BASE_URL}/admin/rules/${encodeURIComponent(deleteInput.trim())}`,
{
method: "DELETE",
headers,
}
);
if (!response.ok) {
throw new Error(await buildErrorMessage(response));
}
await handleRefresh();
setDeleteInput("");
setStatus({ tone: "success", message: "Rule deleted." });
} catch (error: any) {
setStatus({ tone: "error", message: error.message || "Failed to delete rule" });
} finally {
setLoading(false);
}
}, [deleteInput, handleRefresh, headers, requireTenant]);
// Check permissions AFTER all hooks are called
if (!canManageRules(role)) {
return (
<main className="mx-auto flex min-h-screen max-w-5xl flex-col gap-10 px-4 pb-16 pt-12 sm:px-6 lg:px-8">
<header className="flex flex-col gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-6 text-slate-100 shadow-lg shadow-slate-950/40">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3 text-base font-semibold">
<span className="inline-flex h-10 w-10 items-center justify-center rounded-2xl bg-gradient-to-br from-sky-400 to-cyan-500 text-slate-950">
IC
</span>
IntegraChat Β· Admin Rules
</div>
<div className="flex items-center gap-4">
<TenantSelector />
<Link href="/" className="text-xs font-semibold uppercase tracking-[0.3em] text-cyan-300 hover:text-white">
β Back Home
</Link>
</div>
</div>
</header>
<div className="rounded-2xl border border-red-500/50 bg-red-500/10 p-8 text-center">
<h2 className="text-2xl font-bold text-red-300 mb-2">Access Denied</h2>
<p className="text-slate-300 mb-4">
You need <strong>Admin</strong> or <strong>Owner</strong> role to manage rules.
</p>
<p className="text-sm text-slate-400">
Your current role: <strong className="text-slate-200">{role.charAt(0).toUpperCase() + role.slice(1)}</strong>
</p>
<p className="text-sm text-slate-400 mt-2">
Please switch your role using the dropdown in the header.
</p>
</div>
<Footer />
</main>
);
}
return (
<main className="mx-auto flex min-h-screen max-w-5xl flex-col gap-10 px-4 pb-16 pt-12 sm:px-6 lg:px-8">
<header className="flex flex-col gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-6 text-slate-100 shadow-lg shadow-slate-950/40">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3 text-base font-semibold">
<span className="inline-flex h-10 w-10 items-center justify-center rounded-2xl bg-gradient-to-br from-sky-400 to-cyan-500 text-slate-950">
IC
</span>
IntegraChat Β· Admin Rule Ingestion
</div>
<div className="flex items-center gap-4">
<TenantSelector />
<Link href="/" className="text-xs font-semibold uppercase tracking-[0.3em] text-cyan-300 hover:text-white">
β Back Home
</Link>
</div>
</div>
<div className="space-y-2">
<p className="text-sm text-slate-300">
Upload governance policies, compliance workflows, and red-flag patterns. Rules are automatically enhanced by LLM and stored in the backend.
</p>
<div className="flex flex-wrap gap-2 text-xs text-slate-400">
<span className="flex items-center gap-1 rounded-full bg-white/5 px-3 py-1">
<span>β¨</span>
<span>LLM Enhanced</span>
</span>
<span className="flex items-center gap-1 rounded-full bg-white/5 px-3 py-1">
<span>π</span>
<span>File Upload</span>
</span>
<span className="flex items-center gap-1 rounded-full bg-white/5 px-3 py-1">
<span>π</span>
<span>Chunk Processing</span>
</span>
</div>
</div>
</header>
<AdminRulesPanel />
<section className="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-2xl shadow-slate-950/40">
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between gap-3">
{lastUpdated && (
<div className="flex items-center gap-2 text-sm text-slate-400">
<span>π</span>
<span>Last updated: {lastUpdated}</span>
</div>
)}
{!lastUpdated && <div></div>}
<button
onClick={handleRefresh}
disabled={loading}
className="flex items-center gap-2 rounded-xl bg-gradient-to-r from-cyan-400 to-blue-500 px-6 py-3 text-sm font-semibold text-slate-950 shadow-lg shadow-cyan-500/30 transition hover:shadow-cyan-500/50 disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? (
<>
<span className="animate-spin">β³</span>
<span>Refreshing...</span>
</>
) : (
<>
<span>π</span>
<span>Refresh Rules</span>
</>
)}
</button>
</div>
<div className="grid gap-6 lg:grid-cols-2">
{/* Left Column: Upload Rules */}
<div className="flex flex-col gap-4 rounded-2xl border border-white/10 bg-slate-900/30 p-6">
<div className="flex items-center gap-2">
<span className="text-lg">π</span>
<h3 className="text-lg font-semibold text-slate-200">Add Rules</h3>
</div>
<label className="flex flex-col gap-2 text-sm font-semibold text-slate-200">
<span>Bulk Upload Rules (one per line)</span>
<textarea
value={rulesInput}
onChange={(e) => setRulesInput(e.target.value)}
placeholder="Block password disclosure requests\nPrevent sharing of API keys\nNo sharing of credit card information"
rows={8}
className="rounded-xl border border-white/10 bg-slate-900/50 px-4 py-3 text-sm text-white placeholder:text-slate-500 outline-none ring-0 transition focus:border-cyan-400 focus:ring-2 focus:ring-cyan-400/20"
/>
<span className="text-xs text-slate-400">
π‘ Tip: Comment lines (starting with #) are automatically ignored
</span>
</label>
<button
onClick={handleUpload}
disabled={loading || !rulesInput.trim()}
className="rounded-xl bg-gradient-to-r from-emerald-400 to-lime-400 px-6 py-3 text-sm font-semibold text-slate-900 shadow-lg shadow-emerald-500/30 transition hover:shadow-emerald-500/50 disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? "β³ Uploading..." : "β
Upload / Append Rules"}
</button>
<div className="flex items-center gap-3 py-2">
<span className="h-px flex-1 bg-white/10"></span>
<span className="text-xs font-semibold uppercase tracking-wider text-slate-400">OR</span>
<span className="h-px flex-1 bg-white/10"></span>
</div>
<label className="flex flex-col gap-2 text-sm font-semibold text-slate-200">
<span>π Upload Rules from File</span>
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={`relative rounded-xl border-2 border-dashed transition-all ${
isDragging
? "border-cyan-400 bg-cyan-500/10 scale-[1.02]"
: "border-white/20 bg-slate-900/50 hover:border-cyan-400/50 hover:bg-slate-900/70"
}`}
>
<input
ref={fileInputRef}
type="file"
accept=".txt,.pdf,.doc,.docx,.md"
onChange={handleFileUpload}
disabled={loading}
className="hidden"
id="file-upload-input"
/>
<label
htmlFor="file-upload-input"
className="flex flex-col items-center justify-center gap-3 p-8 cursor-pointer"
>
{isDragging ? (
<>
<span className="text-4xl animate-bounce">π₯</span>
<span className="text-sm font-semibold text-cyan-300">Drop file here</span>
</>
) : (
<>
<span className="text-4xl">π</span>
<div className="text-center">
<span className="text-sm font-semibold text-slate-200">
Drag & drop file here
</span>
<span className="text-xs text-slate-400 block mt-1">or click to browse</span>
</div>
<button
type="button"
disabled={loading}
className="mt-2 rounded-lg bg-gradient-to-r from-cyan-500 to-blue-500 px-4 py-2 text-xs font-semibold text-slate-900 transition hover:from-cyan-400 hover:to-blue-400 disabled:opacity-50"
>
Choose File
</button>
</>
)}
</label>
</div>
<span className="text-xs text-slate-400">
Supported: TXT, PDF, DOC, DOCX, MD β’ Files processed server-side with LLM enhancement
</span>
</label>
</div>
{/* Right Column: Delete Rules */}
<div className="flex flex-col gap-4 rounded-2xl border border-white/10 bg-slate-900/30 p-6">
<div className="flex items-center gap-2">
<span className="text-lg">ποΈ</span>
<h3 className="text-lg font-semibold text-slate-200">Delete Rule</h3>
</div>
<label className="flex flex-col gap-2 text-sm font-semibold text-slate-200">
<span>Enter exact rule text to remove</span>
<textarea
value={deleteInput}
onChange={(e) => setDeleteInput(e.target.value)}
placeholder="Paste the exact rule text here to delete it..."
rows={8}
className="rounded-xl border border-white/10 bg-slate-900/50 px-4 py-3 text-sm text-white placeholder:text-slate-500 outline-none ring-0 transition focus:border-rose-400 focus:ring-2 focus:ring-rose-400/20"
/>
<span className="text-xs text-slate-400">
β οΈ This action cannot be undone. Make sure the text matches exactly.
</span>
</label>
<button
onClick={handleDelete}
disabled={loading || !deleteInput.trim()}
className="rounded-xl border-2 border-rose-500 bg-rose-500/10 px-6 py-3 text-sm font-semibold text-rose-300 transition hover:bg-rose-500/20 hover:border-rose-400 disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? "β³ Deleting..." : "ποΈ Delete Rule"}
</button>
</div>
</div>
{status && (
<div
className={`rounded-xl border-2 px-5 py-4 text-sm font-medium shadow-lg ${
status.tone === "error"
? "border-rose-500/50 bg-rose-500/10 text-rose-200 shadow-rose-500/20"
: status.tone === "success"
? "border-emerald-500/50 bg-emerald-500/10 text-emerald-200 shadow-emerald-500/20"
: "border-cyan-500/50 bg-cyan-500/10 text-cyan-200 shadow-cyan-500/20"
}`}
>
<div className="flex items-start gap-3">
<span className="text-lg">
{status.tone === "error" ? "β" : status.tone === "success" ? "β
" : "βΉοΈ"}
</span>
<span className="flex-1">{status.message}</span>
</div>
</div>
)}
<div className="rounded-2xl border border-white/10 bg-gradient-to-br from-slate-900/60 to-slate-950/60 shadow-xl">
<div className="flex items-center justify-between border-b border-white/10 bg-white/5 px-6 py-4">
<div className="flex items-center gap-3">
<span className="text-xl">π</span>
<h3 className="text-base font-semibold uppercase tracking-[0.2em] text-slate-300">Rule Set</h3>
</div>
<div className="flex items-center gap-3">
<button
onClick={handleRefresh}
disabled={loading}
className="flex items-center gap-2 rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-4 py-2 text-xs font-semibold text-cyan-300 transition hover:bg-cyan-500/20 hover:border-cyan-400/50 disabled:opacity-50 disabled:cursor-not-allowed"
title="Refresh rules from database"
>
{loading ? (
<>
<span className="animate-spin">β³</span>
<span>Refreshing...</span>
</>
) : (
<>
<span>π</span>
<span>Refresh</span>
</>
)}
</button>
<div className="flex items-center gap-2 rounded-full bg-cyan-500/20 px-4 py-2">
<span className="text-sm font-semibold text-cyan-300">{rules.length}</span>
<span className="text-xs text-slate-400">entries</span>
</div>
</div>
</div>
<div className="overflow-x-auto max-h-[500px] overflow-y-auto">
<table className="w-full text-left text-sm">
<thead className="sticky top-0 bg-slate-900/95 backdrop-blur-sm text-xs uppercase tracking-[0.2em] text-slate-400">
<tr>
<th className="px-6 py-4 font-semibold">#</th>
<th className="px-6 py-4 font-semibold">Rule</th>
</tr>
</thead>
<tbody>
{rules.length === 0 && (
<tr>
<td colSpan={2} className="px-6 py-12 text-center">
<div className="flex flex-col items-center gap-3">
<span className="text-4xl">π</span>
<p className="text-slate-400">No rules loaded</p>
<p className="text-xs text-slate-500">Use the refresh button above to load rules</p>
</div>
</td>
</tr>
)}
{rules.map((rule, idx) => {
const explanation = ruleExplanations[rule];
const isExpanded = expandedRules.has(rule);
const isLoading = loadingExplanations.has(rule);
return (
<React.Fragment key={`${rule}-${idx}`}>
<tr className="border-t border-white/5 transition hover:bg-white/5">
<td className="px-6 py-4 text-slate-400 font-mono">{idx + 1}</td>
<td className="px-6 py-4">
<div className="flex items-center justify-between gap-3">
<span className="text-slate-200 flex-1">{rule}</span>
<button
onClick={() => toggleRuleExplanation(rule)}
className="flex items-center gap-2 rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-3 py-1.5 text-xs font-semibold text-cyan-300 transition hover:bg-cyan-500/20 hover:border-cyan-400/50"
title={isExpanded ? "Hide explanation" : "Show explanation"}
>
{isLoading ? (
<>
<span className="animate-spin">β³</span>
<span>Loading...</span>
</>
) : isExpanded ? (
<>
<span>βΌ</span>
<span>Hide</span>
</>
) : (
<>
<span>βΆ</span>
<span>Explain</span>
</>
)}
</button>
</div>
</td>
</tr>
{isExpanded && explanation && (
<tr>
<td colSpan={2} className="px-6 py-4">
<RuleExplanation
explanation={explanation.explanation}
examples={explanation.examples}
missingPatterns={explanation.missing_patterns}
edgeCases={explanation.edge_cases}
improvements={explanation.improvements}
severity={explanation.severity}
/>
</td>
</tr>
)}
{isExpanded && !explanation && !isLoading && (
<tr>
<td colSpan={2} className="px-6 py-4 text-center text-slate-400 text-sm">
No explanation available for this rule.
</td>
</tr>
)}
</React.Fragment>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</section>
<Footer />
</main>
);
}
|