Files
EpicNext-Cms/src/app/admin/import/audit/audit-client.tsx
T
openhands bebd65c056
Deploy / release (push) Skipped
Deploy / deploy (push) Successful in 1m52s
fix: refactor audit to SSE streaming, improve error handling
- Changed from blocking JSON endpoint to SSE streaming (like sync-all/repair-icons)
- Progress updates during each audit phase with item counts
- Proper error handling with typed AuditEvent for every failure path
- AbortController support for the client
- Shows real-time progress for each check section
2026-07-21 15:33:15 +02:00

449 lines
13 KiB
TypeScript

"use client";
import {
AlertCircle,
CheckCircle2,
ClipboardList,
ExternalLink,
Loader2,
SearchX,
} from "lucide-react";
import { useCallback, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { adminFetch } from "@/lib/admin-fetch";
interface AuditIssue {
type: string;
severity: "error" | "warning" | "info";
classname?: string;
itemId?: number;
catalogId?: number;
message: string;
sourceName?: string;
}
interface MissingFromSource {
sourceName: string;
sourceId: string;
classname: string;
itemName: string;
}
interface AuditSummary {
totalItemsBase: number;
totalCatalogItems: number;
missingCatalog: number;
orphanedCatalog: number;
missingNitro: number;
missingIcon: number;
duplicates: number;
missingFromSourcesTotal: number;
}
interface AuditEvent {
type: string;
message?: string;
current?: number;
total?: number;
section?: string;
issues?: AuditIssue[];
missingFromSources?: MissingFromSource[];
summary?: AuditSummary;
}
const TYPE_LABELS: Record<string, string> = {
missing_catalog: "No catalog entry",
orphaned_catalog: "Orphaned catalog reference",
missing_nitro: "Missing .nitro file",
missing_icon: "Missing icon file",
duplicate_classname: "Duplicate classname",
source_fetch_failed: "Source fetch failed",
};
export function AuditClient() {
const [loading, setLoading] = useState(false);
const [progress, setProgress] = useState("");
const [activeTab, setActiveTab] = useState<"issues" | "sources">("issues");
const [issues, setIssues] = useState<AuditIssue[]>([]);
const [missingFromSources, setMissingFromSources] = useState<
MissingFromSource[]
>([]);
const [summary, setSummary] = useState<AuditSummary | null>(null);
const [checkProgress, setCheckProgress] = useState<{
section: string;
current: number;
total: number;
} | null>(null);
const abortRef = useRef<AbortController | null>(null);
const runAudit = useCallback(async () => {
setLoading(true);
setProgress("Starting audit…");
setIssues([]);
setMissingFromSources([]);
setSummary(null);
setCheckProgress(null);
setActiveTab("issues");
const abort = new AbortController();
abortRef.current = abort;
try {
const res = await adminFetch("/api/admin/import/audit", {
method: "POST",
signal: abort.signal,
});
if (!res.body) {
toast.error("No response stream");
setLoading(false);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const parts = buf.split("\n\n");
buf = parts.pop() ?? "";
for (const part of parts) {
if (!part.startsWith("data: ")) continue;
try {
const evt = JSON.parse(part.slice(6)) as AuditEvent;
if (evt.type === "progress") {
setProgress(evt.message ?? "");
}
if (evt.type === "items_loaded") {
setProgress(`Loaded ${evt.total} items_base entries`);
}
if (evt.type === "catalog_loaded") {
setProgress(`Loaded ${evt.total} catalog_items entries`);
}
if (evt.type === "checking") {
setProgress(`Checking ${evt.section}…`);
if (evt.total) {
setCheckProgress({
section: evt.section ?? "",
current: evt.current ?? 0,
total: evt.total,
});
}
}
if (evt.type === "batch_complete") {
setIssues(evt.issues ?? []);
setMissingFromSources(evt.missingFromSources ?? []);
if (evt.summary) setSummary(evt.summary);
setCheckProgress(null);
setProgress("Done");
if (
evt.issues &&
evt.issues.filter((i) => i.severity === "error").length > 0
) {
toast.error(
`${evt.issues.filter((i) => i.severity === "error").length} error(s) found`,
);
} else if (
evt.issues &&
evt.issues.filter((i) => i.severity === "warning").length > 0
) {
toast.warning("Warnings found");
} else {
toast.success("No issues found");
}
}
if (evt.type === "error") {
setProgress(`ERROR: ${evt.message ?? ""}`);
toast.error(evt.message ?? "Audit failed");
}
} catch {
// skip parse errors
}
}
}
} catch (err) {
if ((err as Error).name !== "AbortError") {
toast.error("Audit request failed");
}
} finally {
setLoading(false);
abortRef.current = null;
}
}, []);
const errors = issues.filter((i) => i.severity === "error");
const warnings = issues.filter((i) => i.severity === "warning");
return (
<div className="space-y-6">
{!summary && (
<Button onClick={runAudit} disabled={loading} size="lg">
{loading ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<ClipboardList className="w-4 h-4 mr-2" />
)}
{loading ? progress || "Running…" : "Run Full Catalog Audit"}
</Button>
)}
{loading && checkProgress && (
<div className="text-sm text-muted-foreground">
{checkProgress.section}: {checkProgress.current} /{" "}
{checkProgress.total}
</div>
)}
{summary && (
<>
{/* Summary cards */}
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-xl border bg-card p-4 space-y-1">
<div className="text-2xl font-bold">{summary.totalItemsBase}</div>
<div className="text-xs text-muted-foreground">
items_base entries
</div>
</div>
<div className="rounded-xl border bg-card p-4 space-y-1">
<div className="text-2xl font-bold">
{summary.totalCatalogItems}
</div>
<div className="text-xs text-muted-foreground">
catalog_items entries
</div>
</div>
<div
className={`rounded-xl border p-4 space-y-1 ${errors.length > 0 ? "border-[var(--admin-error-border)] bg-[var(--admin-error-subtle)]" : "bg-card"}`}
>
<div
className={`text-2xl font-bold ${errors.length > 0 ? "text-[var(--admin-error)]" : ""}`}
>
{errors.length}
</div>
<div className="text-xs text-muted-foreground">Errors</div>
</div>
<div
className={`rounded-xl border p-4 space-y-1 ${warnings.length > 0 ? "border-[var(--admin-warning-border)] bg-[var(--admin-warning-subtle)]" : "bg-card"}`}
>
<div
className={`text-2xl font-bold ${warnings.length > 0 ? "text-[var(--admin-warning)]" : ""}`}
>
{warnings.length}
</div>
<div className="text-xs text-muted-foreground">Warnings</div>
</div>
</div>
{/* Quick stats */}
<div className="grid gap-2 sm:grid-cols-3 text-sm">
<div className="flex items-center gap-2">
{summary.missingCatalog > 0 ? (
<AlertCircle className="w-4 h-4 text-[var(--admin-warning)]" />
) : (
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
)}
<span>{summary.missingCatalog} items without catalog entry</span>
</div>
<div className="flex items-center gap-2">
{summary.orphanedCatalog > 0 ? (
<AlertCircle className="w-4 h-4 text-[var(--admin-error)]" />
) : (
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
)}
<span>{summary.orphanedCatalog} orphaned catalog references</span>
</div>
<div className="flex items-center gap-2">
{summary.missingNitro > 0 ? (
<AlertCircle className="w-4 h-4 text-[var(--admin-error)]" />
) : (
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
)}
<span>{summary.missingNitro} items without .nitro</span>
</div>
<div className="flex items-center gap-2">
{summary.missingIcon > 0 ? (
<AlertCircle className="w-4 h-4 text-[var(--admin-warning)]" />
) : (
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
)}
<span>{summary.missingIcon} items without icon</span>
</div>
<div className="flex items-center gap-2">
{summary.duplicates > 0 ? (
<AlertCircle className="w-4 h-4 text-[var(--admin-error)]" />
) : (
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
)}
<span>{summary.duplicates} duplicate classnames</span>
</div>
<div className="flex items-center gap-2">
{summary.missingFromSourcesTotal > 0 ? (
<AlertCircle className="w-4 h-4 text-[var(--admin-warning)]" />
) : (
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
)}
<span>
{summary.missingFromSourcesTotal} items missing from clone
sources
</span>
</div>
</div>
{/* Tabs */}
{issues.length > 0 || missingFromSources.length > 0 ? (
<div className="border-b border-border">
<div className="flex gap-4">
<button
type="button"
onClick={() => setActiveTab("issues")}
className={`pb-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === "issues"
? "border-primary text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground"
}`}
>
Issues ({issues.length})
</button>
<button
type="button"
onClick={() => setActiveTab("sources")}
className={`pb-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === "sources"
? "border-primary text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground"
}`}
>
Missing from sources ({missingFromSources.length})
</button>
</div>
</div>
) : null}
{/* Issues list */}
{activeTab === "issues" && issues.length > 0 && (
<div className="space-y-2">
{issues.map((issue) => (
<div
key={issue.message}
className={`rounded-xl border p-4 text-sm ${
issue.severity === "error"
? "border-[var(--admin-error-border)] bg-[var(--admin-error-subtle)]"
: issue.severity === "warning"
? "border-[var(--admin-warning-border)] bg-[var(--admin-warning-subtle)]"
: "bg-card"
}`}
>
<div className="flex items-start gap-2">
<AlertCircle
className={`w-4 h-4 mt-0.5 shrink-0 ${
issue.severity === "error"
? "text-[var(--admin-error)]"
: issue.severity === "warning"
? "text-[var(--admin-warning)]"
: "text-[var(--admin-text-muted)]"
}`}
/>
<div className="space-y-0.5 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span
className={`font-medium ${
issue.severity === "error"
? "text-[var(--admin-error)]"
: issue.severity === "warning"
? "text-[var(--admin-warning)]"
: "text-[var(--admin-text-muted)]"
}`}
>
{TYPE_LABELS[issue.type] || issue.type}
</span>
{issue.classname && (
<code className="text-xs bg-background/50 px-1.5 py-0.5 rounded font-mono">
{issue.classname}
</code>
)}
{issue.sourceName && (
<span className="text-xs text-muted-foreground">
source: {issue.sourceName}
</span>
)}
</div>
<p className="text-muted-foreground">{issue.message}</p>
</div>
</div>
</div>
))}
</div>
)}
{/* Missing from sources list */}
{activeTab === "sources" && missingFromSources.length > 0 && (
<div className="space-y-2">
{missingFromSources.map((item) => (
<div
key={`${item.sourceId}-${item.classname}`}
className="rounded-xl border bg-card p-3 text-sm flex items-center gap-2"
>
<ExternalLink className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<code className="font-mono text-xs">{item.classname}</code>
<span className="text-xs text-muted-foreground">
— {item.itemName}
</span>
<span className="text-xs text-muted-foreground ml-auto">
in {item.sourceName}
</span>
</div>
))}
</div>
)}
{activeTab === "issues" &&
issues.length === 0 &&
missingFromSources.length === 0 && (
<div className="rounded-xl border bg-card p-12 text-center text-muted-foreground">
<CheckCircle2 className="w-12 h-12 mx-auto mb-3 text-[var(--admin-success)]" />
<p className="text-lg font-medium">No issues found</p>
<p className="text-sm">Your catalog is clean!</p>
</div>
)}
<Button
variant="outline"
onClick={() => {
setSummary(null);
setIssues([]);
setMissingFromSources([]);
setProgress("");
setCheckProgress(null);
}}
>
Run Again
</Button>
</>
)}
{!loading && !summary && (
<div className="rounded-xl border bg-card p-12 text-center text-muted-foreground">
<SearchX className="w-12 h-12 mx-auto mb-3 opacity-40" />
<p>
Run a full audit to check for missing catalog entries, broken
references, missing files, and items available from clone sources.
</p>
</div>
)}
</div>
);
}