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
This commit is contained in:
1 parent
19e4e10b1d
commit
bebd65c056
3 files changed
+444
-203
No files matched your search
@@ -8,7 +8,7 @@ import {
|
||||
Loader2,
|
||||
SearchX,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { adminFetch } from "@/lib/admin-fetch";
|
||||
@@ -30,26 +30,27 @@ interface MissingFromSource {
|
||||
itemName: string;
|
||||
}
|
||||
|
||||
interface AuditResult {
|
||||
issues: AuditIssue[];
|
||||
missingFromSources: MissingFromSource[];
|
||||
summary: {
|
||||
totalItemsBase: number;
|
||||
totalCatalogItems: number;
|
||||
missingCatalog: number;
|
||||
orphanedCatalog: number;
|
||||
missingNitro: number;
|
||||
missingIcon: number;
|
||||
duplicates: number;
|
||||
missingFromSourcesTotal: number;
|
||||
};
|
||||
interface AuditSummary {
|
||||
totalItemsBase: number;
|
||||
totalCatalogItems: number;
|
||||
missingCatalog: number;
|
||||
orphanedCatalog: number;
|
||||
missingNitro: number;
|
||||
missingIcon: number;
|
||||
duplicates: number;
|
||||
missingFromSourcesTotal: number;
|
||||
}
|
||||
|
||||
const ICON_COLORS: Record<string, string> = {
|
||||
error: "text-[var(--admin-error)]",
|
||||
warning: "text-[var(--admin-warning)]",
|
||||
info: "text-[var(--admin-text-muted)]",
|
||||
};
|
||||
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",
|
||||
@@ -58,53 +59,137 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
missing_icon: "Missing icon file",
|
||||
duplicate_classname: "Duplicate classname",
|
||||
source_fetch_failed: "Source fetch failed",
|
||||
sources_list_failed: "Sources list failed",
|
||||
};
|
||||
|
||||
export function AuditClient() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [result, setResult] = useState<AuditResult | null>(null);
|
||||
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);
|
||||
setResult(null);
|
||||
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",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
signal: abort.signal,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
toast.error(data.error || "Audit failed");
|
||||
setProgress("");
|
||||
if (!res.body) {
|
||||
toast.error("No response stream");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setResult(data);
|
||||
toast.success("Audit complete");
|
||||
} catch {
|
||||
toast.error("Audit request failed");
|
||||
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);
|
||||
setProgress("");
|
||||
abortRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const hasIssues = result && result.issues.length > 0;
|
||||
const errors = result?.issues.filter((i) => i.severity === "error") ?? [];
|
||||
const warnings = result?.issues.filter((i) => i.severity === "warning") ?? [];
|
||||
const errors = issues.filter((i) => i.severity === "error");
|
||||
const warnings = issues.filter((i) => i.severity === "warning");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{!result && (
|
||||
{!summary && (
|
||||
<Button onClick={runAudit} disabled={loading} size="lg">
|
||||
{loading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-2" />
|
||||
@@ -115,21 +200,26 @@ export function AuditClient() {
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
{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">
|
||||
{result.summary.totalItemsBase}
|
||||
</div>
|
||||
<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">
|
||||
{result.summary.totalCatalogItems}
|
||||
{summary.totalCatalogItems}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
catalog_items entries
|
||||
@@ -160,64 +250,60 @@ export function AuditClient() {
|
||||
{/* Quick stats */}
|
||||
<div className="grid gap-2 sm:grid-cols-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
{result.summary.missingCatalog > 0 ? (
|
||||
{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>
|
||||
{result.summary.missingCatalog} items without catalog entry
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result.summary.orphanedCatalog > 0 ? (
|
||||
<AlertCircle className="w-4 h-4 text-[var(--admin-error)]" />
|
||||
) : (
|
||||
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
|
||||
)}
|
||||
<span>
|
||||
{result.summary.orphanedCatalog} orphaned catalog references
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result.summary.missingNitro > 0 ? (
|
||||
<AlertCircle className="w-4 h-4 text-[var(--admin-error)]" />
|
||||
) : (
|
||||
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
|
||||
)}
|
||||
<span>{result.summary.missingNitro} items without .nitro</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result.summary.missingIcon > 0 ? (
|
||||
<AlertCircle className="w-4 h-4 text-[var(--admin-warning)]" />
|
||||
) : (
|
||||
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
|
||||
)}
|
||||
<span>{result.summary.missingIcon} items without icon</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result.summary.duplicates > 0 ? (
|
||||
<AlertCircle className="w-4 h-4 text-[var(--admin-error)]" />
|
||||
) : (
|
||||
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
|
||||
)}
|
||||
<span>{result.summary.duplicates} duplicate classnames</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result.summary.missingFromSourcesTotal > 0 ? (
|
||||
<AlertCircle className="w-4 h-4 text-[var(--admin-warning)]" />
|
||||
) : (
|
||||
<CheckCircle2 className="w-4 h-4 text-[var(--admin-success)]" />
|
||||
)}
|
||||
<span>
|
||||
{result.summary.missingFromSourcesTotal} items missing from
|
||||
clone sources
|
||||
{summary.missingFromSourcesTotal} items missing from clone
|
||||
sources
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
{hasIssues || result.missingFromSources.length > 0 ? (
|
||||
{issues.length > 0 || missingFromSources.length > 0 ? (
|
||||
<div className="border-b border-border">
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
@@ -229,7 +315,7 @@ export function AuditClient() {
|
||||
: "border-transparent text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
Issues ({result.issues.length})
|
||||
Issues ({issues.length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -240,16 +326,16 @@ export function AuditClient() {
|
||||
: "border-transparent text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
Missing from sources ({result.missingFromSources.length})
|
||||
Missing from sources ({missingFromSources.length})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Issues list */}
|
||||
{activeTab === "issues" && hasIssues && (
|
||||
{activeTab === "issues" && issues.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{result.issues.map((issue) => (
|
||||
{issues.map((issue) => (
|
||||
<div
|
||||
key={issue.message}
|
||||
className={`rounded-xl border p-4 text-sm ${
|
||||
@@ -262,12 +348,24 @@ export function AuditClient() {
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle
|
||||
className={`w-4 h-4 mt-0.5 shrink-0 ${ICON_COLORS[issue.severity]}`}
|
||||
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 ${ICON_COLORS[issue.severity]}`}
|
||||
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>
|
||||
@@ -291,9 +389,9 @@ export function AuditClient() {
|
||||
)}
|
||||
|
||||
{/* Missing from sources list */}
|
||||
{activeTab === "sources" && result.missingFromSources.length > 0 && (
|
||||
{activeTab === "sources" && missingFromSources.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{result.missingFromSources.map((item) => (
|
||||
{missingFromSources.map((item) => (
|
||||
<div
|
||||
key={`${item.sourceId}-${item.classname}`}
|
||||
className="rounded-xl border bg-card p-3 text-sm flex items-center gap-2"
|
||||
@@ -312,8 +410,8 @@ export function AuditClient() {
|
||||
)}
|
||||
|
||||
{activeTab === "issues" &&
|
||||
!hasIssues &&
|
||||
result.missingFromSources.length === 0 && (
|
||||
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>
|
||||
@@ -324,8 +422,11 @@ export function AuditClient() {
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setResult(null);
|
||||
setSummary(null);
|
||||
setIssues([]);
|
||||
setMissingFromSources([]);
|
||||
setProgress("");
|
||||
setCheckProgress(null);
|
||||
}}
|
||||
>
|
||||
Run Again
|
||||
@@ -333,7 +434,7 @@ export function AuditClient() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{!loading && !result && (
|
||||
{!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>
|
||||
|
||||
@@ -1,13 +1,46 @@
|
||||
import { withAdmin } from "@/lib/api-handler";
|
||||
import { apiError, apiOk } from "@/lib/api-response";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { runCatalogAudit } from "@/lib/services/catalog-audit";
|
||||
|
||||
function sseEvent(data: unknown): string {
|
||||
return `data: ${JSON.stringify(data)}\n\n`;
|
||||
}
|
||||
|
||||
export const POST = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async () => {
|
||||
try {
|
||||
const result = await runCatalogAudit();
|
||||
return apiOk(result as unknown as Record<string, unknown>);
|
||||
} catch (err) {
|
||||
return apiError(`Audit failed: ${(err as Error).message}`, 500);
|
||||
}
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
const send = (data: unknown) => {
|
||||
try {
|
||||
controller.enqueue(encoder.encode(sseEvent(data)));
|
||||
} catch {
|
||||
/* stream closed */
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await runCatalogAudit(send);
|
||||
} catch (err) {
|
||||
send({
|
||||
type: "error",
|
||||
message: `Audit threw: ${(err as Error).message}`,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,23 @@ import { listSources } from "@/lib/services/clone-sources";
|
||||
import { getFurniAssetDirs } from "@/lib/services/furni-asset-dirs";
|
||||
import { ensureDirectories } from "./furni-import";
|
||||
|
||||
export interface AuditEvent {
|
||||
type:
|
||||
| "progress"
|
||||
| "items_loaded"
|
||||
| "catalog_loaded"
|
||||
| "checking"
|
||||
| "batch_complete"
|
||||
| "error";
|
||||
message?: string;
|
||||
current?: number;
|
||||
total?: number;
|
||||
section?: string;
|
||||
issues?: AuditIssue[];
|
||||
missingFromSources?: MissingFromSource[];
|
||||
summary?: AuditSummary;
|
||||
}
|
||||
|
||||
export interface AuditIssue {
|
||||
type: string;
|
||||
severity: "error" | "warning" | "info";
|
||||
@@ -23,68 +40,106 @@ export interface MissingFromSource {
|
||||
itemName: string;
|
||||
}
|
||||
|
||||
export interface AuditResult {
|
||||
issues: AuditIssue[];
|
||||
missingFromSources: MissingFromSource[];
|
||||
summary: {
|
||||
totalItemsBase: number;
|
||||
totalCatalogItems: number;
|
||||
missingCatalog: number;
|
||||
orphanedCatalog: number;
|
||||
missingNitro: number;
|
||||
missingIcon: number;
|
||||
duplicates: number;
|
||||
missingFromSourcesTotal: number;
|
||||
};
|
||||
export interface AuditSummary {
|
||||
totalItemsBase: number;
|
||||
totalCatalogItems: number;
|
||||
missingCatalog: number;
|
||||
orphanedCatalog: number;
|
||||
missingNitro: number;
|
||||
missingIcon: number;
|
||||
duplicates: number;
|
||||
missingFromSourcesTotal: number;
|
||||
}
|
||||
|
||||
export async function runCatalogAudit(
|
||||
onProgress?: (msg: string) => void,
|
||||
): Promise<AuditResult> {
|
||||
onEvent?: (evt: AuditEvent) => void,
|
||||
): Promise<void> {
|
||||
const issues: AuditIssue[] = [];
|
||||
const missingFromSources: MissingFromSource[] = [];
|
||||
|
||||
onProgress?.("Loading directories…");
|
||||
await ensureDirectories();
|
||||
const { iconDir, nitroDir } = await getFurniAssetDirs();
|
||||
try {
|
||||
await ensureDirectories();
|
||||
} catch (err) {
|
||||
onEvent?.({
|
||||
type: "error",
|
||||
message: `ensureDirectories failed: ${(err as Error).message}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
onProgress?.("Loading items_base…");
|
||||
const items = await prisma.$queryRaw<
|
||||
Array<{ id: number; item_name: string; public_name: string; type: string }>
|
||||
>`SELECT id, item_name, public_name, type FROM items_base ORDER BY id`;
|
||||
let iconDir: string;
|
||||
let nitroDir: string;
|
||||
try {
|
||||
const dirs = await getFurniAssetDirs();
|
||||
iconDir = dirs.iconDir;
|
||||
nitroDir = dirs.nitroDir;
|
||||
} catch (err) {
|
||||
onEvent?.({
|
||||
type: "error",
|
||||
message: `getFurniAssetDirs failed: ${(err as Error).message}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
onProgress?.("Loading catalog_items…");
|
||||
const catalogItems = await prisma.$queryRaw<
|
||||
Array<{ id: number; item_ids: string; catalog_name: string }>
|
||||
>`SELECT id, item_ids, catalog_name FROM catalog_items ORDER BY id`;
|
||||
onEvent?.({ type: "progress", message: "Loading items_base…" });
|
||||
|
||||
const summary = {
|
||||
totalItemsBase: items.length,
|
||||
totalCatalogItems: catalogItems.length,
|
||||
missingCatalog: 0,
|
||||
orphanedCatalog: 0,
|
||||
missingNitro: 0,
|
||||
missingIcon: 0,
|
||||
duplicates: 0,
|
||||
missingFromSourcesTotal: 0,
|
||||
};
|
||||
let items: Array<{
|
||||
id: number;
|
||||
item_name: string;
|
||||
public_name: string;
|
||||
type: string;
|
||||
}>;
|
||||
try {
|
||||
items = await prisma.$queryRaw<
|
||||
Array<{
|
||||
id: number;
|
||||
item_name: string;
|
||||
public_name: string;
|
||||
type: string;
|
||||
}>
|
||||
>`SELECT id, item_name, public_name, type FROM items_base ORDER BY id`;
|
||||
} catch (err) {
|
||||
onEvent?.({
|
||||
type: "error",
|
||||
message: `items_base query failed: ${(err as Error).message}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
onEvent?.({ type: "items_loaded", total: items.length });
|
||||
|
||||
onEvent?.({ type: "progress", message: "Loading catalog_items…" });
|
||||
|
||||
let catalogItems: Array<{
|
||||
id: number;
|
||||
item_ids: string;
|
||||
catalog_name: string;
|
||||
}>;
|
||||
try {
|
||||
catalogItems = await prisma.$queryRaw<
|
||||
Array<{ id: number; item_ids: string; catalog_name: string }>
|
||||
>`SELECT id, item_ids, catalog_name FROM catalog_items ORDER BY id`;
|
||||
} catch (err) {
|
||||
onEvent?.({
|
||||
type: "error",
|
||||
message: `catalog_items query failed: ${(err as Error).message}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
onEvent?.({ type: "catalog_loaded", total: catalogItems.length });
|
||||
|
||||
// Build lookup: set of items_base IDs that have catalog entries
|
||||
const itemIdsWithCatalog = new Set<number>();
|
||||
const itemNamesWithCatalog = new Set<string>();
|
||||
for (const ci of catalogItems) {
|
||||
const ids = ci.item_ids.split(";").map(Number).filter(Boolean);
|
||||
for (const id of ids) {
|
||||
itemIdsWithCatalog.add(id);
|
||||
}
|
||||
itemNamesWithCatalog.add(ci.catalog_name);
|
||||
}
|
||||
|
||||
// Build items_base lookup by id and name
|
||||
const itemById = new Map<number, (typeof items)[0]>();
|
||||
const itemByName = new Map<string, (typeof items)[0]>();
|
||||
const classnameCount = new Map<string, number>();
|
||||
|
||||
for (const item of items) {
|
||||
itemById.set(item.id, item);
|
||||
itemByName.set(item.item_name, item);
|
||||
@@ -94,10 +149,15 @@ export async function runCatalogAudit(
|
||||
);
|
||||
}
|
||||
|
||||
onProgress?.("Checking items_base entries…");
|
||||
for (const item of items) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "missing_catalog",
|
||||
total: items.length,
|
||||
});
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
if (!itemIdsWithCatalog.has(item.id)) {
|
||||
summary.missingCatalog++;
|
||||
issues.push({
|
||||
type: "missing_catalog",
|
||||
severity: "warning",
|
||||
@@ -106,12 +166,20 @@ export async function runCatalogAudit(
|
||||
message: `"${item.item_name}" (ID ${item.id}) has no catalog_items entry — not purchasable`,
|
||||
});
|
||||
}
|
||||
if (i % 100 === 0) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "missing_catalog",
|
||||
current: i,
|
||||
total: items.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.("Checking for duplicate classnames…");
|
||||
onEvent?.({ type: "checking", section: "duplicates" });
|
||||
|
||||
for (const [name, count] of classnameCount) {
|
||||
if (count > 1) {
|
||||
summary.duplicates++;
|
||||
issues.push({
|
||||
type: "duplicate_classname",
|
||||
severity: "error",
|
||||
@@ -121,12 +189,17 @@ export async function runCatalogAudit(
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.("Checking catalog_items for orphaned references…");
|
||||
for (const ci of catalogItems) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "orphaned_catalog",
|
||||
total: catalogItems.length,
|
||||
});
|
||||
|
||||
for (let i = 0; i < catalogItems.length; i++) {
|
||||
const ci = catalogItems[i];
|
||||
const ids = ci.item_ids.split(";").map(Number).filter(Boolean);
|
||||
for (const id of ids) {
|
||||
if (!itemById.has(id)) {
|
||||
summary.orphanedCatalog++;
|
||||
issues.push({
|
||||
type: "orphaned_catalog",
|
||||
severity: "error",
|
||||
@@ -135,13 +208,26 @@ export async function runCatalogAudit(
|
||||
});
|
||||
}
|
||||
}
|
||||
if (i % 200 === 0) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "orphaned_catalog",
|
||||
current: i,
|
||||
total: catalogItems.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.("Checking .nitro files…");
|
||||
for (const item of items) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "missing_nitro",
|
||||
total: items.length,
|
||||
});
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const nitroPath = path.join(nitroDir, `${item.item_name}.nitro`);
|
||||
if (!existsSync(nitroPath)) {
|
||||
summary.missingNitro++;
|
||||
issues.push({
|
||||
type: "missing_nitro",
|
||||
severity: "error",
|
||||
@@ -150,13 +236,22 @@ export async function runCatalogAudit(
|
||||
message: `"${item.item_name}" (ID ${item.id}) has no .nitro file`,
|
||||
});
|
||||
}
|
||||
if (i % 100 === 0) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "missing_nitro",
|
||||
current: i,
|
||||
total: items.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.("Checking icon files…");
|
||||
for (const item of items) {
|
||||
onEvent?.({ type: "checking", section: "missing_icon", total: items.length });
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const iconPath = path.join(iconDir, `${item.item_name}_icon.png`);
|
||||
if (!existsSync(iconPath)) {
|
||||
summary.missingIcon++;
|
||||
issues.push({
|
||||
type: "missing_icon",
|
||||
severity: "warning",
|
||||
@@ -165,50 +260,62 @@ export async function runCatalogAudit(
|
||||
message: `"${item.item_name}" (ID ${item.id}) has no icon file`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.("Comparing with clone sources…");
|
||||
try {
|
||||
const sources = await listSources();
|
||||
for (const source of sources) {
|
||||
try {
|
||||
const entries = await fetchSourceFurnidata(source.furnidataUrl);
|
||||
for (const entry of entries) {
|
||||
if (!itemByName.has(entry.classname)) {
|
||||
missingFromSources.push({
|
||||
sourceName: source.name,
|
||||
sourceId: source.id,
|
||||
classname: entry.classname,
|
||||
itemName: entry.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
issues.push({
|
||||
type: "source_fetch_failed",
|
||||
severity: "error",
|
||||
sourceName: source.name,
|
||||
message: `Failed to fetch furnidata from "${source.name}"`,
|
||||
});
|
||||
}
|
||||
if (i % 100 === 0) {
|
||||
onEvent?.({
|
||||
type: "checking",
|
||||
section: "missing_icon",
|
||||
current: i,
|
||||
total: items.length,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
issues.push({
|
||||
type: "sources_list_failed",
|
||||
severity: "error",
|
||||
message: `Failed to list clone sources: ${(err as Error).message}`,
|
||||
});
|
||||
}
|
||||
|
||||
summary.missingFromSourcesTotal = missingFromSources.length;
|
||||
onEvent?.({ type: "progress", message: "Comparing with clone sources…" });
|
||||
|
||||
const sources = await listSources();
|
||||
for (const source of sources) {
|
||||
try {
|
||||
const entries = await fetchSourceFurnidata(source.furnidataUrl);
|
||||
for (const entry of entries) {
|
||||
if (!itemByName.has(entry.classname)) {
|
||||
missingFromSources.push({
|
||||
sourceName: source.name,
|
||||
sourceId: source.id,
|
||||
classname: entry.classname,
|
||||
itemName: entry.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
issues.push({
|
||||
type: "source_fetch_failed",
|
||||
severity: "error",
|
||||
sourceName: source.name,
|
||||
message: `Failed to fetch furnidata from "${source.name}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort issues: errors first, then by type
|
||||
issues.sort((a, b) => {
|
||||
const sev = { error: 0, warning: 1, info: 2 };
|
||||
const diff = (sev[a.severity] ?? 0) - (sev[b.severity] ?? 0);
|
||||
if (diff !== 0) return diff;
|
||||
return a.type.localeCompare(b.type);
|
||||
return (sev[a.severity] ?? 0) - (sev[b.severity] ?? 0);
|
||||
});
|
||||
|
||||
return { issues, missingFromSources, summary };
|
||||
const summary: AuditSummary = {
|
||||
totalItemsBase: items.length,
|
||||
totalCatalogItems: catalogItems.length,
|
||||
missingCatalog: issues.filter((i) => i.type === "missing_catalog").length,
|
||||
orphanedCatalog: issues.filter((i) => i.type === "orphaned_catalog").length,
|
||||
missingNitro: issues.filter((i) => i.type === "missing_nitro").length,
|
||||
missingIcon: issues.filter((i) => i.type === "missing_icon").length,
|
||||
duplicates: issues.filter((i) => i.type === "duplicate_classname").length,
|
||||
missingFromSourcesTotal: missingFromSources.length,
|
||||
};
|
||||
|
||||
onEvent?.({
|
||||
type: "batch_complete",
|
||||
issues,
|
||||
missingFromSources,
|
||||
summary,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user