🔨 Fixed the status updates on Import
This commit is contained in:
@@ -14,7 +14,7 @@
|
||||
"test:coverage": "jest --coverage",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build",
|
||||
"codegen": "graphql-codegen --config codegen.yml",
|
||||
"codegen": "wait-on http-get://localhost:3000/graphql/health && graphql-codegen",
|
||||
"codegen:watch": "graphql-codegen --config codegen.yml --watch"
|
||||
},
|
||||
"author": "Rishi Ghan",
|
||||
|
||||
@@ -7,10 +7,11 @@ import { useShallow } from "zustand/react/shallow";
|
||||
import axios from "axios";
|
||||
import {
|
||||
useGetJobResultStatisticsQuery,
|
||||
useGetCachedImportStatisticsQuery,
|
||||
useGetImportStatisticsQuery,
|
||||
useStartIncrementalImportMutation
|
||||
} from "../../graphql/generated";
|
||||
import { RealTimeImportStats } from "./RealTimeImportStats";
|
||||
import { useImportSessionStatus } from "../../hooks/useImportSessionStatus";
|
||||
|
||||
interface ImportProps {
|
||||
path: string;
|
||||
@@ -23,6 +24,7 @@ interface ImportProps {
|
||||
export const Import = (props: ImportProps): ReactElement => {
|
||||
const queryClient = useQueryClient();
|
||||
const [socketReconnectTrigger, setSocketReconnectTrigger] = useState(0);
|
||||
const [importError, setImportError] = useState<string | null>(null);
|
||||
const { importJobQueue, getSocket, disconnectSocket } = useStore(
|
||||
useShallow((state) => ({
|
||||
importJobQueue: state.importJobQueue,
|
||||
@@ -35,8 +37,13 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
onSuccess: (data) => {
|
||||
if (data.startIncrementalImport.success) {
|
||||
importJobQueue.setStatus("running");
|
||||
setImportError(null);
|
||||
}
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Failed to start import:", error);
|
||||
setImportError(error?.message || "Failed to start import. Please try again.");
|
||||
},
|
||||
});
|
||||
|
||||
const { mutate: initiateImport } = useMutation({
|
||||
@@ -50,10 +57,31 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
},
|
||||
});
|
||||
|
||||
// Force re-import mutation - re-imports all files regardless of import status
|
||||
const { mutate: forceReImport, isPending: isForceReImporting } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const sessionId = localStorage.getItem("sessionId") || "";
|
||||
return await axios.request({
|
||||
url: `http://localhost:3000/api/library/forceReImport`,
|
||||
method: "POST",
|
||||
data: { sessionId },
|
||||
});
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
console.log("Force re-import initiated:", response.data);
|
||||
importJobQueue.setStatus("running");
|
||||
setImportError(null);
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Failed to start force re-import:", error);
|
||||
setImportError(error?.response?.data?.message || error?.message || "Failed to start force re-import. Please try again.");
|
||||
},
|
||||
});
|
||||
|
||||
const { data, isError, isLoading, refetch } = useGetJobResultStatisticsQuery();
|
||||
|
||||
// Get cached import statistics to determine if Start Import button should be shown
|
||||
const { data: cachedStats } = useGetCachedImportStatisticsQuery(
|
||||
// Get import statistics to determine if Start Import button should be shown
|
||||
const { data: importStats } = useGetImportStatisticsQuery(
|
||||
{},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
@@ -61,25 +89,43 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
}
|
||||
);
|
||||
|
||||
// Use custom hook for definitive import session status tracking
|
||||
// NO POLLING - relies on Socket.IO events only
|
||||
const importSession = useImportSessionStatus();
|
||||
|
||||
const hasActiveSession = importSession.isActive;
|
||||
|
||||
// Determine if we should show the Start Import button
|
||||
const hasNewFiles = cachedStats?.getCachedImportStatistics?.success &&
|
||||
cachedStats.getCachedImportStatistics.stats &&
|
||||
cachedStats.getCachedImportStatistics.stats.newFiles > 0 &&
|
||||
cachedStats.getCachedImportStatistics.stats.pendingFiles === 0;
|
||||
const hasNewFiles = importStats?.getImportStatistics?.success &&
|
||||
importStats.getImportStatistics.stats &&
|
||||
importStats.getImportStatistics.stats.newFiles > 0;
|
||||
|
||||
useEffect(() => {
|
||||
const socket = getSocket("/");
|
||||
const handleQueueDrained = () => refetch();
|
||||
const handleCoverExtracted = () => refetch();
|
||||
|
||||
const handleSessionStarted = () => {
|
||||
importJobQueue.setStatus("running");
|
||||
};
|
||||
|
||||
const handleSessionCompleted = () => {
|
||||
refetch();
|
||||
importJobQueue.setStatus("drained");
|
||||
};
|
||||
|
||||
socket.on("LS_IMPORT_QUEUE_DRAINED", handleQueueDrained);
|
||||
socket.on("LS_COVER_EXTRACTED", handleCoverExtracted);
|
||||
socket.on("IMPORT_SESSION_STARTED", handleSessionStarted);
|
||||
socket.on("IMPORT_SESSION_COMPLETED", handleSessionCompleted);
|
||||
|
||||
return () => {
|
||||
socket.off("LS_IMPORT_QUEUE_DRAINED", handleQueueDrained);
|
||||
socket.off("LS_COVER_EXTRACTED", handleCoverExtracted);
|
||||
socket.off("IMPORT_SESSION_STARTED", handleSessionStarted);
|
||||
socket.off("IMPORT_SESSION_COMPLETED", handleSessionCompleted);
|
||||
};
|
||||
}, [getSocket, refetch, socketReconnectTrigger]);
|
||||
}, [getSocket, refetch, importJobQueue, socketReconnectTrigger]);
|
||||
|
||||
/**
|
||||
* Toggles import queue pause/resume state
|
||||
@@ -97,9 +143,20 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts smart import, resetting session if queue was drained
|
||||
* Starts smart import with race condition prevention
|
||||
*/
|
||||
const handleStartSmartImport = () => {
|
||||
const handleStartSmartImport = async () => {
|
||||
// Clear any previous errors
|
||||
setImportError(null);
|
||||
|
||||
// Check for active session before starting using definitive status
|
||||
if (hasActiveSession) {
|
||||
setImportError(
|
||||
`Cannot start import: An import session "${importSession.sessionId}" is already active. Please wait for it to complete.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (importJobQueue.status === "drained") {
|
||||
localStorage.removeItem("sessionId");
|
||||
disconnectSocket("/");
|
||||
@@ -117,6 +174,40 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles force re-import - re-imports all files to fix indexing issues
|
||||
*/
|
||||
const handleForceReImport = async () => {
|
||||
setImportError(null);
|
||||
|
||||
// Check for active session before starting using definitive status
|
||||
if (hasActiveSession) {
|
||||
setImportError(
|
||||
`Cannot start import: An import session "${importSession.sessionId}" is already active. Please wait for it to complete.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.confirm(
|
||||
"This will re-import ALL files in your library folder, even those already imported. " +
|
||||
"This can help fix Elasticsearch indexing issues. Continue?"
|
||||
)) {
|
||||
if (importJobQueue.status === "drained") {
|
||||
localStorage.removeItem("sessionId");
|
||||
disconnectSocket("/");
|
||||
setTimeout(() => {
|
||||
getSocket("/");
|
||||
setSocketReconnectTrigger(prev => prev + 1);
|
||||
setTimeout(() => {
|
||||
forceReImport();
|
||||
}, 500);
|
||||
}, 100);
|
||||
} else {
|
||||
forceReImport();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders pause/resume controls based on queue status
|
||||
*/
|
||||
@@ -185,11 +276,6 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
</header>
|
||||
|
||||
<div className="mx-auto max-w-screen-xl px-4 py-4 sm:px-6 sm:py-8 lg:px-8">
|
||||
{/* Real-Time Import Statistics Widget */}
|
||||
<div className="mb-6 max-w-screen-lg">
|
||||
<RealTimeImportStats />
|
||||
</div>
|
||||
|
||||
<article
|
||||
role="alert"
|
||||
className="rounded-lg max-w-screen-md border-s-4 border-blue-500 bg-blue-50 p-4 dark:border-s-4 dark:border-blue-600 dark:bg-blue-300 dark:text-slate-600"
|
||||
@@ -209,65 +295,102 @@ export const Import = (props: ImportProps): ReactElement => {
|
||||
</div>
|
||||
</article>
|
||||
|
||||
{/* Start Smart Import Button - shown when there are new files and no import is running */}
|
||||
{hasNewFiles &&
|
||||
(importJobQueue.status === "drained" || importJobQueue.status === undefined) && (
|
||||
{/* Import Statistics */}
|
||||
<div className="my-6 max-w-screen-lg">
|
||||
<RealTimeImportStats />
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{importError && (
|
||||
<div className="my-6 max-w-screen-lg rounded-lg border-s-4 border-red-500 bg-red-50 dark:bg-red-900/20 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="w-6 h-6 text-red-600 dark:text-red-400 mt-0.5">
|
||||
<i className="h-6 w-6 icon-[solar--danger-circle-bold]"></i>
|
||||
</span>
|
||||
<div className="flex-1">
|
||||
<p className="font-semibold text-red-800 dark:text-red-300">
|
||||
Import Error
|
||||
</p>
|
||||
<p className="text-sm text-red-700 dark:text-red-400 mt-1">
|
||||
{importError}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setImportError(null)}
|
||||
className="text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-200"
|
||||
>
|
||||
<span className="w-5 h-5">
|
||||
<i className="h-5 w-5 icon-[solar--close-circle-bold]"></i>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Active Session Warning */}
|
||||
{hasActiveSession && !hasNewFiles && (
|
||||
<div className="my-6 max-w-screen-lg rounded-lg border-s-4 border-yellow-500 bg-yellow-50 dark:bg-yellow-900/20 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="w-6 h-6 text-yellow-600 dark:text-yellow-400 mt-0.5">
|
||||
<i className="h-6 w-6 icon-[solar--info-circle-bold]"></i>
|
||||
</span>
|
||||
<div className="flex-1">
|
||||
<p className="font-semibold text-yellow-800 dark:text-yellow-300">
|
||||
Import In Progress
|
||||
</p>
|
||||
<p className="text-sm text-yellow-700 dark:text-yellow-400 mt-1">
|
||||
An import session is currently active. New imports cannot be started until it completes.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Action Buttons */}
|
||||
<div className="my-6 max-w-screen-lg flex flex-col sm:flex-row gap-3">
|
||||
{/* Start Smart Import Button - shown when there are new files, no active session, and no import is running */}
|
||||
{hasNewFiles &&
|
||||
!hasActiveSession &&
|
||||
(importJobQueue.status === "drained" || importJobQueue.status === undefined) && (
|
||||
<button
|
||||
className="flex space-x-1 sm:mt-0 sm:flex-row sm:items-center rounded-lg border border-green-400 dark:border-green-200 bg-green-200 px-5 py-3 text-gray-500 hover:bg-transparent hover:text-green-600 focus:outline-none focus:ring active:text-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
onClick={handleStartSmartImport}
|
||||
disabled={isStartingImport}
|
||||
disabled={isStartingImport || hasActiveSession}
|
||||
>
|
||||
<span className="text-md font-medium">
|
||||
{isStartingImport ? "Starting Import..." : `Start Smart Import (${cachedStats?.getCachedImportStatistics?.stats?.newFiles} new files)`}
|
||||
{isStartingImport
|
||||
? "Starting Import..."
|
||||
: importStats?.getImportStatistics?.stats?.alreadyImported === 0
|
||||
? `Start Import (${importStats?.getImportStatistics?.stats?.newFiles} files)`
|
||||
: `Start Incremental Import (${importStats?.getImportStatistics?.stats?.newFiles} new files)`
|
||||
}
|
||||
</span>
|
||||
<span className="w-6 h-6">
|
||||
<i className="h-6 w-6 icon-[solar--file-left-bold-duotone]"></i>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(importJobQueue.status === "running" ||
|
||||
importJobQueue.status === "paused") && (
|
||||
<>
|
||||
<span className="flex items-center my-5 max-w-screen-lg">
|
||||
<span className="text-xl text-slate-500 dark:text-slate-200 pr-5">
|
||||
Import Activity
|
||||
{/* Force Re-Import Button - always shown when no import is running */}
|
||||
{!hasActiveSession &&
|
||||
(importJobQueue.status === "drained" || importJobQueue.status === undefined) && (
|
||||
<button
|
||||
className="flex space-x-1 sm:mt-0 sm:flex-row sm:items-center rounded-lg border border-orange-400 dark:border-orange-200 bg-orange-200 px-5 py-3 text-gray-700 hover:bg-transparent hover:text-orange-600 focus:outline-none focus:ring active:text-orange-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
onClick={handleForceReImport}
|
||||
disabled={isForceReImporting || hasActiveSession}
|
||||
title="Re-import all files to fix Elasticsearch indexing issues"
|
||||
>
|
||||
<span className="text-md font-medium">
|
||||
{isForceReImporting ? "Starting Re-Import..." : "Force Re-Import All Files"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-slate-200 dark:bg-slate-400"></span>
|
||||
<span className="w-6 h-6">
|
||||
<i className="h-6 w-6 icon-[solar--refresh-bold-duotone]"></i>
|
||||
</span>
|
||||
<div className="mt-5 flex flex-col gap-4 sm:mt-0 sm:flex-row sm:items-center">
|
||||
<dl className="grid grid-cols-2 gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col rounded-lg bg-green-100 dark:bg-green-200 px-4 py-6 text-center">
|
||||
<dd className="text-3xl text-green-600 md:text-5xl">
|
||||
{importJobQueue.successfulJobCount}
|
||||
</dd>
|
||||
<dt className="text-lg font-medium text-gray-500">
|
||||
imported
|
||||
</dt>
|
||||
</div>
|
||||
<div className="flex flex-col rounded-lg bg-red-100 dark:bg-red-200 px-4 py-6 text-center">
|
||||
<dd className="text-3xl text-red-600 md:text-5xl">
|
||||
{importJobQueue.failedJobCount}
|
||||
</dd>
|
||||
<dt className="text-lg font-medium text-gray-500">
|
||||
failed
|
||||
</dt>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col dark:text-slate-200 text-slate-400">
|
||||
<dd>{renderQueueControls(importJobQueue.status)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<div className="flex">
|
||||
<span className="mt-2 dark:text-slate-200 text-slate-400">
|
||||
Imported: <span>{importJobQueue.mostRecentImport}</span>
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{/* Import activity is now shown in the RealTimeImportStats component above */}
|
||||
|
||||
{!isLoading && !isEmpty(data?.getJobResultStatistics) && (
|
||||
<div className="max-w-screen-lg">
|
||||
|
||||
@@ -1,288 +1,229 @@
|
||||
import React, { ReactElement, useEffect, useState } from "react";
|
||||
import { useGetCachedImportStatisticsQuery } from "../../graphql/generated";
|
||||
import {
|
||||
useGetImportStatisticsQuery,
|
||||
useStartIncrementalImportMutation
|
||||
} from "../../graphql/generated";
|
||||
import { useStore } from "../../store";
|
||||
import { format } from "date-fns";
|
||||
|
||||
interface ImportStatsData {
|
||||
totalLocalFiles: number;
|
||||
alreadyImported: number;
|
||||
newFiles: number;
|
||||
percentageImported: string;
|
||||
pendingFiles: number;
|
||||
lastUpdated: string;
|
||||
}
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useImportSessionStatus } from "../../hooks/useImportSessionStatus";
|
||||
|
||||
/**
|
||||
* Real-time import statistics widget
|
||||
* Displays live statistics from the file watcher and updates via Socket.IO
|
||||
* Import statistics with card-based layout and progress bar
|
||||
* Updates in real-time via the useImportSessionStatus hook
|
||||
*/
|
||||
export const RealTimeImportStats = (): ReactElement => {
|
||||
const [stats, setStats] = useState<ImportStatsData | null>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const getSocket = useStore((state) => state.getSocket);
|
||||
|
||||
// Fetch initial cached statistics
|
||||
const {
|
||||
data: cachedStats,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useGetCachedImportStatisticsQuery(
|
||||
{},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
refetchInterval: false,
|
||||
}
|
||||
const [importError, setImportError] = useState<string | null>(null);
|
||||
const { getSocket, disconnectSocket, importJobQueue } = useStore(
|
||||
useShallow((state) => ({
|
||||
getSocket: state.getSocket,
|
||||
disconnectSocket: state.disconnectSocket,
|
||||
importJobQueue: state.importJobQueue,
|
||||
}))
|
||||
);
|
||||
|
||||
// Set initial stats from GraphQL query
|
||||
useEffect(() => {
|
||||
if (cachedStats?.getCachedImportStatistics?.success && cachedStats.getCachedImportStatistics.stats) {
|
||||
setStats({
|
||||
totalLocalFiles: cachedStats.getCachedImportStatistics.stats.totalLocalFiles,
|
||||
alreadyImported: cachedStats.getCachedImportStatistics.stats.alreadyImported,
|
||||
newFiles: cachedStats.getCachedImportStatistics.stats.newFiles,
|
||||
percentageImported: cachedStats.getCachedImportStatistics.stats.percentageImported,
|
||||
pendingFiles: cachedStats.getCachedImportStatistics.stats.pendingFiles,
|
||||
lastUpdated: cachedStats.getCachedImportStatistics.lastUpdated || new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}, [cachedStats]);
|
||||
// Get filesystem statistics (new files vs already imported)
|
||||
const { data: importStats, isLoading, refetch: refetchStats } = useGetImportStatisticsQuery(
|
||||
{},
|
||||
{ refetchOnWindowFocus: false, refetchInterval: false }
|
||||
);
|
||||
|
||||
// Setup Socket.IO listener for real-time updates
|
||||
// Get definitive import session status (handles Socket.IO events internally)
|
||||
const importSession = useImportSessionStatus();
|
||||
|
||||
const { mutate: startIncrementalImport, isPending: isStartingImport } = useStartIncrementalImportMutation({
|
||||
onSuccess: (data) => {
|
||||
if (data.startIncrementalImport.success) {
|
||||
importJobQueue.setStatus("running");
|
||||
setImportError(null);
|
||||
}
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Failed to start import:", error);
|
||||
setImportError(error?.message || "Failed to start import. Please try again.");
|
||||
},
|
||||
});
|
||||
|
||||
const stats = importStats?.getImportStatistics?.stats;
|
||||
const hasNewFiles = stats && stats.newFiles > 0;
|
||||
|
||||
// Refetch filesystem stats when import completes
|
||||
useEffect(() => {
|
||||
if (importSession.isComplete && importSession.status === "completed") {
|
||||
console.log("[RealTimeImportStats] Import completed, refetching filesystem stats");
|
||||
refetchStats();
|
||||
importJobQueue.setStatus("drained");
|
||||
}
|
||||
}, [importSession.isComplete, importSession.status, refetchStats, importJobQueue]);
|
||||
|
||||
// Listen to filesystem change events to refetch stats
|
||||
useEffect(() => {
|
||||
const socket = getSocket("/");
|
||||
|
||||
const handleConnect = () => {
|
||||
setIsConnected(true);
|
||||
console.log("Real-time import stats: Socket connected");
|
||||
const handleFilesystemChange = () => {
|
||||
refetchStats();
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
setIsConnected(false);
|
||||
console.log("Real-time import stats: Socket disconnected");
|
||||
};
|
||||
|
||||
const handleStatsUpdate = (data: any) => {
|
||||
console.log("Real-time import stats update received:", data);
|
||||
if (data.stats) {
|
||||
setStats({
|
||||
totalLocalFiles: data.stats.totalLocalFiles,
|
||||
alreadyImported: data.stats.alreadyImported,
|
||||
newFiles: data.stats.newFiles,
|
||||
percentageImported: data.stats.percentageImported,
|
||||
pendingFiles: data.stats.pendingFiles || 0,
|
||||
lastUpdated: data.lastUpdated || new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
socket.on("connect", handleConnect);
|
||||
socket.on("disconnect", handleDisconnect);
|
||||
socket.on("IMPORT_STATISTICS_UPDATED", handleStatsUpdate);
|
||||
|
||||
// Check initial connection state
|
||||
if (socket.connected) {
|
||||
setIsConnected(true);
|
||||
}
|
||||
// File system changes that affect import statistics
|
||||
socket.on("LS_FILE_ADDED", handleFilesystemChange);
|
||||
socket.on("LS_FILE_REMOVED", handleFilesystemChange);
|
||||
socket.on("LS_FILE_CHANGED", handleFilesystemChange);
|
||||
socket.on("LS_DIRECTORY_ADDED", handleFilesystemChange);
|
||||
socket.on("LS_DIRECTORY_REMOVED", handleFilesystemChange);
|
||||
socket.on("LS_LIBRARY_STATISTICS", handleFilesystemChange);
|
||||
|
||||
return () => {
|
||||
socket.off("connect", handleConnect);
|
||||
socket.off("disconnect", handleDisconnect);
|
||||
socket.off("IMPORT_STATISTICS_UPDATED", handleStatsUpdate);
|
||||
socket.off("LS_FILE_ADDED", handleFilesystemChange);
|
||||
socket.off("LS_FILE_REMOVED", handleFilesystemChange);
|
||||
socket.off("LS_FILE_CHANGED", handleFilesystemChange);
|
||||
socket.off("LS_DIRECTORY_ADDED", handleFilesystemChange);
|
||||
socket.off("LS_DIRECTORY_REMOVED", handleFilesystemChange);
|
||||
socket.off("LS_LIBRARY_STATISTICS", handleFilesystemChange);
|
||||
};
|
||||
}, [getSocket]);
|
||||
}, [getSocket, refetchStats]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-slate-700 p-6">
|
||||
<div className="flex justify-center items-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
|
||||
<span className="ml-3 text-gray-600 dark:text-gray-300">
|
||||
Loading statistics...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
const handleStartImport = async () => {
|
||||
setImportError(null);
|
||||
|
||||
// Check if import is already active using definitive status
|
||||
if (importSession.isActive) {
|
||||
setImportError(
|
||||
`Cannot start import: An import session "${importSession.sessionId}" is already active. Please wait for it to complete.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
if (importJobQueue.status === "drained") {
|
||||
localStorage.removeItem("sessionId");
|
||||
disconnectSocket("/");
|
||||
setTimeout(() => {
|
||||
getSocket("/");
|
||||
setTimeout(() => {
|
||||
const sessionId = localStorage.getItem("sessionId") || "";
|
||||
startIncrementalImport({ sessionId });
|
||||
}, 500);
|
||||
}, 100);
|
||||
} else {
|
||||
const sessionId = localStorage.getItem("sessionId") || "";
|
||||
startIncrementalImport({ sessionId });
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading || !stats) {
|
||||
return <div className="text-gray-500 dark:text-gray-400">Loading...</div>;
|
||||
}
|
||||
|
||||
// Determine button text based on whether there are already imported files
|
||||
const isFirstImport = stats.alreadyImported === 0;
|
||||
const buttonText = isFirstImport
|
||||
? `Start Import (${stats.newFiles} files)`
|
||||
: `Start Incremental Import (${stats.newFiles} new files)`;
|
||||
|
||||
// Calculate display statistics
|
||||
const displayStats = importSession.isActive && importSession.stats
|
||||
? {
|
||||
totalFiles: importSession.stats.filesQueued + stats.alreadyImported,
|
||||
filesQueued: importSession.stats.filesQueued,
|
||||
filesSucceeded: importSession.stats.filesSucceeded,
|
||||
}
|
||||
: {
|
||||
totalFiles: stats.totalLocalFiles,
|
||||
filesQueued: stats.newFiles,
|
||||
filesSucceeded: stats.alreadyImported,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-red-200 dark:border-red-600 bg-red-50 dark:bg-red-900/20 p-6">
|
||||
<div className="flex items-center">
|
||||
<span className="w-6 h-6 text-red-600">
|
||||
<div className="space-y-6">
|
||||
{/* Error Message */}
|
||||
{importError && (
|
||||
<div className="rounded-lg border-l-4 border-red-500 bg-red-50 dark:bg-red-900/20 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="w-6 h-6 text-red-600 dark:text-red-400 mt-0.5">
|
||||
<i className="h-6 w-6 icon-[solar--danger-circle-bold]"></i>
|
||||
</span>
|
||||
<span className="ml-3 text-red-600 dark:text-red-400">
|
||||
Error loading statistics
|
||||
<div className="flex-1">
|
||||
<p className="font-semibold text-red-800 dark:text-red-300">Import Error</p>
|
||||
<p className="text-sm text-red-700 dark:text-red-400 mt-1">{importError}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setImportError(null)}
|
||||
className="text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-200"
|
||||
>
|
||||
<span className="w-5 h-5">
|
||||
<i className="h-5 w-5 icon-[solar--close-circle-bold]"></i>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
|
||||
// Handle cache not initialized or no stats available
|
||||
if (!stats || cachedStats?.getCachedImportStatistics?.success === false) {
|
||||
return (
|
||||
<div className="rounded-lg border border-yellow-200 dark:border-yellow-600 bg-yellow-50 dark:bg-yellow-900/20 p-6">
|
||||
{/* Import Button - only show when there are new files and no active import */}
|
||||
{hasNewFiles && !importSession.isActive && (
|
||||
<button
|
||||
onClick={handleStartImport}
|
||||
disabled={isStartingImport}
|
||||
className="w-full flex items-center justify-center gap-2 rounded-lg bg-green-500 hover:bg-green-600 disabled:bg-gray-400 px-6 py-3 text-white font-medium transition-colors disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="w-6 h-6">
|
||||
<i className="h-6 w-6 icon-[solar--file-left-bold-duotone]"></i>
|
||||
</span>
|
||||
<span>{isStartingImport ? "Starting Import..." : buttonText}</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Active Import Progress Bar */}
|
||||
{importSession.isActive && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<span className="w-6 h-6 text-yellow-600">
|
||||
<i className="h-6 w-6 icon-[solar--info-circle-bold]"></i>
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Importing {importSession.stats?.filesSucceeded || 0} / {importSession.stats?.filesQueued || 0}...
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-white">
|
||||
{Math.round(importSession.progress)}%
|
||||
</span>
|
||||
<div className="ml-3">
|
||||
<p className="font-medium text-yellow-800 dark:text-yellow-300">
|
||||
Statistics Cache Initializing
|
||||
</p>
|
||||
<p className="text-sm text-yellow-700 dark:text-yellow-400 mt-1">
|
||||
{cachedStats?.getCachedImportStatistics?.message || "The file watcher is starting up. Statistics will appear shortly."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => refetch()}
|
||||
className="flex items-center gap-1 px-3 py-2 text-sm rounded-lg border border-yellow-400 bg-yellow-100 dark:bg-yellow-800 text-yellow-700 dark:text-yellow-200 hover:bg-yellow-200 dark:hover:bg-yellow-700 transition-colors"
|
||||
title="Retry"
|
||||
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3 overflow-hidden">
|
||||
<div
|
||||
className="bg-blue-600 dark:bg-blue-500 h-3 rounded-full transition-all duration-300 relative"
|
||||
style={{ width: `${importSession.progress}%` }}
|
||||
>
|
||||
<span className="w-4 h-4">
|
||||
<i className="h-4 w-4 icon-[solar--refresh-bold]"></i>
|
||||
</span>
|
||||
Retry
|
||||
</button>
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-shimmer"></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const percentageValue = typeof stats.percentageImported === 'number'
|
||||
? stats.percentageImported
|
||||
: parseFloat(stats.percentageImported);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-slate-700 p-6">
|
||||
{/* Header with connection status */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
|
||||
<span className="w-6 h-6 mr-2">
|
||||
<i className="h-6 w-6 icon-[solar--chart-bold-duotone]"></i>
|
||||
</span>
|
||||
Real-Time Folder Statistics
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs font-semibold ${
|
||||
isConnected
|
||||
? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
|
||||
: "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`h-2 w-2 rounded-full ${
|
||||
isConnected ? "bg-green-600 animate-pulse" : "bg-gray-400"
|
||||
}`}
|
||||
></span>
|
||||
{isConnected ? "Live" : "Offline"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Statistics Grid */}
|
||||
<dl className="grid grid-cols-2 gap-4 sm:grid-cols-5 mb-4">
|
||||
<div className="flex flex-col rounded-lg bg-blue-100 dark:bg-blue-900/30 px-4 py-4 text-center">
|
||||
<dd className="text-2xl font-bold text-blue-600 dark:text-blue-400 md:text-3xl">
|
||||
{stats.totalLocalFiles}
|
||||
</dd>
|
||||
<dt className="text-sm font-medium text-gray-600 dark:text-gray-300">
|
||||
Total Files
|
||||
</dt>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col rounded-lg bg-green-100 dark:bg-green-900/30 px-4 py-4 text-center">
|
||||
<dd className="text-2xl font-bold text-green-600 dark:text-green-400 md:text-3xl">
|
||||
{stats.newFiles}
|
||||
</dd>
|
||||
<dt className="text-sm font-medium text-gray-600 dark:text-gray-300">
|
||||
New Files
|
||||
</dt>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col rounded-lg bg-yellow-100 dark:bg-yellow-900/30 px-4 py-4 text-center">
|
||||
<dd className="text-2xl font-bold text-yellow-600 dark:text-yellow-400 md:text-3xl">
|
||||
{stats.alreadyImported}
|
||||
</dd>
|
||||
<dt className="text-sm font-medium text-gray-600 dark:text-gray-300">
|
||||
Imported
|
||||
</dt>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col rounded-lg bg-orange-100 dark:bg-orange-900/30 px-4 py-4 text-center">
|
||||
<dd className="text-2xl font-bold text-orange-600 dark:text-orange-400 md:text-3xl">
|
||||
{stats.pendingFiles}
|
||||
</dd>
|
||||
<dt className="text-sm font-medium text-gray-600 dark:text-gray-300">
|
||||
Pending
|
||||
</dt>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col rounded-lg bg-purple-100 dark:bg-purple-900/30 px-4 py-4 text-center">
|
||||
<dd className="text-2xl font-bold text-purple-600 dark:text-purple-400 md:text-3xl">
|
||||
{!isNaN(percentageValue) ? percentageValue.toFixed(1) : '0.0'}%
|
||||
</dd>
|
||||
<dt className="text-sm font-medium text-gray-600 dark:text-gray-300">
|
||||
In Library
|
||||
</dt>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{/* Last Updated */}
|
||||
<div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 pt-2 border-t border-gray-200 dark:border-gray-600">
|
||||
<span className="flex items-center">
|
||||
<span className="w-4 h-4 mr-1">
|
||||
<i className="h-4 w-4 icon-[solar--clock-circle-line-duotone]"></i>
|
||||
</span>
|
||||
Last updated: {format(new Date(stats.lastUpdated), "MMM d, yyyy 'at' h:mm:ss a")}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => refetch()}
|
||||
className="flex items-center gap-1 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
|
||||
title="Refresh statistics"
|
||||
>
|
||||
<span className="w-4 h-4">
|
||||
<i className="h-4 w-4 icon-[solar--refresh-bold]"></i>
|
||||
</span>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Info message about pending files */}
|
||||
{stats.pendingFiles > 0 && (
|
||||
<div className="mt-4 rounded-lg border-s-4 border-orange-500 bg-orange-50 dark:bg-orange-900/20 p-3">
|
||||
<p className="text-sm text-orange-700 dark:text-orange-300">
|
||||
<span className="font-semibold">{stats.pendingFiles}</span> file{stats.pendingFiles !== 1 ? 's are' : ' is'} being stabilized before import (write in progress).
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Info message about new files */}
|
||||
{stats.newFiles > 0 && stats.pendingFiles === 0 && (
|
||||
<div className="mt-4 rounded-lg border-s-4 border-green-500 bg-green-50 dark:bg-green-900/20 p-3">
|
||||
<p className="text-sm text-green-700 dark:text-green-300">
|
||||
<span className="font-semibold">{stats.newFiles}</span> new file{stats.newFiles !== 1 ? 's are' : ' is'} ready to be imported.
|
||||
</p>
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
{/* Files Detected Card */}
|
||||
<div className="rounded-lg p-6 text-center" style={{ backgroundColor: '#6b7280' }}>
|
||||
<div className="text-4xl font-bold text-white mb-2">
|
||||
{displayStats.totalFiles}
|
||||
</div>
|
||||
<div className="text-sm text-gray-200 font-medium">
|
||||
files detected
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* All caught up message */}
|
||||
{stats.newFiles === 0 && stats.pendingFiles === 0 && stats.totalLocalFiles > 0 && (
|
||||
<div className="mt-4 rounded-lg border-s-4 border-blue-500 bg-blue-50 dark:bg-blue-900/20 p-3">
|
||||
<p className="text-sm text-blue-700 dark:text-blue-300 flex items-center">
|
||||
<span className="w-5 h-5 mr-2">
|
||||
<i className="h-5 w-5 icon-[solar--check-circle-bold]"></i>
|
||||
</span>
|
||||
All files in the folder are already imported!
|
||||
</p>
|
||||
{/* To Import Card */}
|
||||
<div className="rounded-lg p-6 text-center" style={{ backgroundColor: '#60a5fa' }}>
|
||||
<div className="text-4xl font-bold text-white mb-2">
|
||||
{displayStats.filesQueued}
|
||||
</div>
|
||||
<div className="text-sm text-gray-100 font-medium">
|
||||
to import
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Already Imported Card */}
|
||||
<div className="rounded-lg p-6 text-center" style={{ backgroundColor: '#d8dab2' }}>
|
||||
<div className="text-4xl font-bold text-gray-800 mb-2">
|
||||
{displayStats.filesSucceeded}
|
||||
</div>
|
||||
<div className="text-sm text-gray-700 font-medium">
|
||||
already imported
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -52,23 +52,6 @@ export type AutoMergeSettingsInput = {
|
||||
onMetadataUpdate?: InputMaybe<Scalars['Boolean']['input']>;
|
||||
};
|
||||
|
||||
export type CachedImportStatistics = {
|
||||
__typename?: 'CachedImportStatistics';
|
||||
lastUpdated?: Maybe<Scalars['String']['output']>;
|
||||
message?: Maybe<Scalars['String']['output']>;
|
||||
stats?: Maybe<CachedImportStats>;
|
||||
success: Scalars['Boolean']['output'];
|
||||
};
|
||||
|
||||
export type CachedImportStats = {
|
||||
__typename?: 'CachedImportStats';
|
||||
alreadyImported: Scalars['Int']['output'];
|
||||
newFiles: Scalars['Int']['output'];
|
||||
pendingFiles: Scalars['Int']['output'];
|
||||
percentageImported: Scalars['String']['output'];
|
||||
totalLocalFiles: Scalars['Int']['output'];
|
||||
};
|
||||
|
||||
export type CanonicalMetadata = {
|
||||
__typename?: 'CanonicalMetadata';
|
||||
ageRating?: Maybe<MetadataField>;
|
||||
@@ -284,6 +267,26 @@ export type ImportJobResult = {
|
||||
success: Scalars['Boolean']['output'];
|
||||
};
|
||||
|
||||
export type ImportSession = {
|
||||
__typename?: 'ImportSession';
|
||||
completedAt?: Maybe<Scalars['String']['output']>;
|
||||
directoryPath?: Maybe<Scalars['String']['output']>;
|
||||
sessionId: Scalars['String']['output'];
|
||||
startedAt: Scalars['String']['output'];
|
||||
stats: ImportSessionStats;
|
||||
status: Scalars['String']['output'];
|
||||
type: Scalars['String']['output'];
|
||||
};
|
||||
|
||||
export type ImportSessionStats = {
|
||||
__typename?: 'ImportSessionStats';
|
||||
filesFailed: Scalars['Int']['output'];
|
||||
filesProcessed: Scalars['Int']['output'];
|
||||
filesQueued: Scalars['Int']['output'];
|
||||
filesSucceeded: Scalars['Int']['output'];
|
||||
totalFiles: Scalars['Int']['output'];
|
||||
};
|
||||
|
||||
export type ImportStatistics = {
|
||||
__typename?: 'ImportStatistics';
|
||||
directory: Scalars['String']['output'];
|
||||
@@ -632,7 +635,7 @@ export type Query = {
|
||||
comics: ComicConnection;
|
||||
/** Fetch resource from Metron API */
|
||||
fetchMetronResource: MetronResponse;
|
||||
getCachedImportStatistics: CachedImportStatistics;
|
||||
getActiveImportSession?: Maybe<ImportSession>;
|
||||
getComicBookGroups: Array<ComicBookGroup>;
|
||||
getComicBooks: ComicBooksResult;
|
||||
/** Get generic ComicVine resource (issues, volumes, etc.) */
|
||||
@@ -1102,11 +1105,6 @@ export type GetImportStatisticsQueryVariables = Exact<{
|
||||
|
||||
export type GetImportStatisticsQuery = { __typename?: 'Query', getImportStatistics: { __typename?: 'ImportStatistics', success: boolean, directory: string, stats: { __typename?: 'ImportStats', totalLocalFiles: number, alreadyImported: number, newFiles: number, percentageImported: string } } };
|
||||
|
||||
export type GetCachedImportStatisticsQueryVariables = Exact<{ [key: string]: never; }>;
|
||||
|
||||
|
||||
export type GetCachedImportStatisticsQuery = { __typename?: 'Query', getCachedImportStatistics: { __typename?: 'CachedImportStatistics', success: boolean, message?: string | null, lastUpdated?: string | null, stats?: { __typename?: 'CachedImportStats', totalLocalFiles: number, alreadyImported: number, newFiles: number, percentageImported: string, pendingFiles: number } | null } };
|
||||
|
||||
export type StartNewImportMutationVariables = Exact<{
|
||||
sessionId: Scalars['String']['input'];
|
||||
}>;
|
||||
@@ -1127,6 +1125,11 @@ export type GetJobResultStatisticsQueryVariables = Exact<{ [key: string]: never;
|
||||
|
||||
export type GetJobResultStatisticsQuery = { __typename?: 'Query', getJobResultStatistics: Array<{ __typename?: 'JobResultStatistics', sessionId: string, earliestTimestamp: string, completedJobs: number, failedJobs: number }> };
|
||||
|
||||
export type GetActiveImportSessionQueryVariables = Exact<{ [key: string]: never; }>;
|
||||
|
||||
|
||||
export type GetActiveImportSessionQuery = { __typename?: 'Query', getActiveImportSession?: { __typename?: 'ImportSession', sessionId: string, type: string, status: string, startedAt: string, completedAt?: string | null, directoryPath?: string | null, stats: { __typename?: 'ImportSessionStats', totalFiles: number, filesQueued: number, filesProcessed: number, filesSucceeded: number, filesFailed: number } } | null };
|
||||
|
||||
export type GetLibraryComicsQueryVariables = Exact<{
|
||||
page?: InputMaybe<Scalars['Int']['input']>;
|
||||
limit?: InputMaybe<Scalars['Int']['input']>;
|
||||
@@ -1907,65 +1910,6 @@ useInfiniteGetImportStatisticsQuery.getKey = (variables?: GetImportStatisticsQue
|
||||
|
||||
useGetImportStatisticsQuery.fetcher = (variables?: GetImportStatisticsQueryVariables, options?: RequestInit['headers']) => fetcher<GetImportStatisticsQuery, GetImportStatisticsQueryVariables>(GetImportStatisticsDocument, variables, options);
|
||||
|
||||
export const GetCachedImportStatisticsDocument = `
|
||||
query GetCachedImportStatistics {
|
||||
getCachedImportStatistics {
|
||||
success
|
||||
message
|
||||
stats {
|
||||
totalLocalFiles
|
||||
alreadyImported
|
||||
newFiles
|
||||
percentageImported
|
||||
pendingFiles
|
||||
}
|
||||
lastUpdated
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const useGetCachedImportStatisticsQuery = <
|
||||
TData = GetCachedImportStatisticsQuery,
|
||||
TError = unknown
|
||||
>(
|
||||
variables?: GetCachedImportStatisticsQueryVariables,
|
||||
options?: Omit<UseQueryOptions<GetCachedImportStatisticsQuery, TError, TData>, 'queryKey'> & { queryKey?: UseQueryOptions<GetCachedImportStatisticsQuery, TError, TData>['queryKey'] }
|
||||
) => {
|
||||
|
||||
return useQuery<GetCachedImportStatisticsQuery, TError, TData>(
|
||||
{
|
||||
queryKey: variables === undefined ? ['GetCachedImportStatistics'] : ['GetCachedImportStatistics', variables],
|
||||
queryFn: fetcher<GetCachedImportStatisticsQuery, GetCachedImportStatisticsQueryVariables>(GetCachedImportStatisticsDocument, variables),
|
||||
...options
|
||||
}
|
||||
)};
|
||||
|
||||
useGetCachedImportStatisticsQuery.getKey = (variables?: GetCachedImportStatisticsQueryVariables) => variables === undefined ? ['GetCachedImportStatistics'] : ['GetCachedImportStatistics', variables];
|
||||
|
||||
export const useInfiniteGetCachedImportStatisticsQuery = <
|
||||
TData = InfiniteData<GetCachedImportStatisticsQuery>,
|
||||
TError = unknown
|
||||
>(
|
||||
variables: GetCachedImportStatisticsQueryVariables,
|
||||
options: Omit<UseInfiniteQueryOptions<GetCachedImportStatisticsQuery, TError, TData>, 'queryKey'> & { queryKey?: UseInfiniteQueryOptions<GetCachedImportStatisticsQuery, TError, TData>['queryKey'] }
|
||||
) => {
|
||||
|
||||
return useInfiniteQuery<GetCachedImportStatisticsQuery, TError, TData>(
|
||||
(() => {
|
||||
const { queryKey: optionsQueryKey, ...restOptions } = options;
|
||||
return {
|
||||
queryKey: optionsQueryKey ?? variables === undefined ? ['GetCachedImportStatistics.infinite'] : ['GetCachedImportStatistics.infinite', variables],
|
||||
queryFn: (metaData) => fetcher<GetCachedImportStatisticsQuery, GetCachedImportStatisticsQueryVariables>(GetCachedImportStatisticsDocument, {...variables, ...(metaData.pageParam ?? {})})(),
|
||||
...restOptions
|
||||
}
|
||||
})()
|
||||
)};
|
||||
|
||||
useInfiniteGetCachedImportStatisticsQuery.getKey = (variables?: GetCachedImportStatisticsQueryVariables) => variables === undefined ? ['GetCachedImportStatistics.infinite'] : ['GetCachedImportStatistics.infinite', variables];
|
||||
|
||||
|
||||
useGetCachedImportStatisticsQuery.fetcher = (variables?: GetCachedImportStatisticsQueryVariables, options?: RequestInit['headers']) => fetcher<GetCachedImportStatisticsQuery, GetCachedImportStatisticsQueryVariables>(GetCachedImportStatisticsDocument, variables, options);
|
||||
|
||||
export const StartNewImportDocument = `
|
||||
mutation StartNewImport($sessionId: String!) {
|
||||
startNewImport(sessionId: $sessionId) {
|
||||
@@ -2076,6 +2020,68 @@ useInfiniteGetJobResultStatisticsQuery.getKey = (variables?: GetJobResultStatist
|
||||
|
||||
useGetJobResultStatisticsQuery.fetcher = (variables?: GetJobResultStatisticsQueryVariables, options?: RequestInit['headers']) => fetcher<GetJobResultStatisticsQuery, GetJobResultStatisticsQueryVariables>(GetJobResultStatisticsDocument, variables, options);
|
||||
|
||||
export const GetActiveImportSessionDocument = `
|
||||
query GetActiveImportSession {
|
||||
getActiveImportSession {
|
||||
sessionId
|
||||
type
|
||||
status
|
||||
startedAt
|
||||
completedAt
|
||||
directoryPath
|
||||
stats {
|
||||
totalFiles
|
||||
filesQueued
|
||||
filesProcessed
|
||||
filesSucceeded
|
||||
filesFailed
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const useGetActiveImportSessionQuery = <
|
||||
TData = GetActiveImportSessionQuery,
|
||||
TError = unknown
|
||||
>(
|
||||
variables?: GetActiveImportSessionQueryVariables,
|
||||
options?: Omit<UseQueryOptions<GetActiveImportSessionQuery, TError, TData>, 'queryKey'> & { queryKey?: UseQueryOptions<GetActiveImportSessionQuery, TError, TData>['queryKey'] }
|
||||
) => {
|
||||
|
||||
return useQuery<GetActiveImportSessionQuery, TError, TData>(
|
||||
{
|
||||
queryKey: variables === undefined ? ['GetActiveImportSession'] : ['GetActiveImportSession', variables],
|
||||
queryFn: fetcher<GetActiveImportSessionQuery, GetActiveImportSessionQueryVariables>(GetActiveImportSessionDocument, variables),
|
||||
...options
|
||||
}
|
||||
)};
|
||||
|
||||
useGetActiveImportSessionQuery.getKey = (variables?: GetActiveImportSessionQueryVariables) => variables === undefined ? ['GetActiveImportSession'] : ['GetActiveImportSession', variables];
|
||||
|
||||
export const useInfiniteGetActiveImportSessionQuery = <
|
||||
TData = InfiniteData<GetActiveImportSessionQuery>,
|
||||
TError = unknown
|
||||
>(
|
||||
variables: GetActiveImportSessionQueryVariables,
|
||||
options: Omit<UseInfiniteQueryOptions<GetActiveImportSessionQuery, TError, TData>, 'queryKey'> & { queryKey?: UseInfiniteQueryOptions<GetActiveImportSessionQuery, TError, TData>['queryKey'] }
|
||||
) => {
|
||||
|
||||
return useInfiniteQuery<GetActiveImportSessionQuery, TError, TData>(
|
||||
(() => {
|
||||
const { queryKey: optionsQueryKey, ...restOptions } = options;
|
||||
return {
|
||||
queryKey: optionsQueryKey ?? variables === undefined ? ['GetActiveImportSession.infinite'] : ['GetActiveImportSession.infinite', variables],
|
||||
queryFn: (metaData) => fetcher<GetActiveImportSessionQuery, GetActiveImportSessionQueryVariables>(GetActiveImportSessionDocument, {...variables, ...(metaData.pageParam ?? {})})(),
|
||||
...restOptions
|
||||
}
|
||||
})()
|
||||
)};
|
||||
|
||||
useInfiniteGetActiveImportSessionQuery.getKey = (variables?: GetActiveImportSessionQueryVariables) => variables === undefined ? ['GetActiveImportSession.infinite'] : ['GetActiveImportSession.infinite', variables];
|
||||
|
||||
|
||||
useGetActiveImportSessionQuery.fetcher = (variables?: GetActiveImportSessionQueryVariables, options?: RequestInit['headers']) => fetcher<GetActiveImportSessionQuery, GetActiveImportSessionQueryVariables>(GetActiveImportSessionDocument, variables, options);
|
||||
|
||||
export const GetLibraryComicsDocument = `
|
||||
query GetLibraryComics($page: Int, $limit: Int, $search: String, $series: String) {
|
||||
comics(page: $page, limit: $limit, search: $search, series: $series) {
|
||||
|
||||
@@ -11,21 +11,6 @@ query GetImportStatistics($directoryPath: String) {
|
||||
}
|
||||
}
|
||||
|
||||
query GetCachedImportStatistics {
|
||||
getCachedImportStatistics {
|
||||
success
|
||||
message
|
||||
stats {
|
||||
totalLocalFiles
|
||||
alreadyImported
|
||||
newFiles
|
||||
percentageImported
|
||||
pendingFiles
|
||||
}
|
||||
lastUpdated
|
||||
}
|
||||
}
|
||||
|
||||
mutation StartNewImport($sessionId: String!) {
|
||||
startNewImport(sessionId: $sessionId) {
|
||||
success
|
||||
@@ -55,3 +40,21 @@ query GetJobResultStatistics {
|
||||
failedJobs
|
||||
}
|
||||
}
|
||||
|
||||
query GetActiveImportSession {
|
||||
getActiveImportSession {
|
||||
sessionId
|
||||
type
|
||||
status
|
||||
startedAt
|
||||
completedAt
|
||||
directoryPath
|
||||
stats {
|
||||
totalFiles
|
||||
filesQueued
|
||||
filesProcessed
|
||||
filesSucceeded
|
||||
filesFailed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
273
src/client/hooks/useImportSessionStatus.ts
Normal file
273
src/client/hooks/useImportSessionStatus.ts
Normal file
@@ -0,0 +1,273 @@
|
||||
import { useEffect, useState, useCallback, useRef } from "react";
|
||||
import { useGetActiveImportSessionQuery } from "../graphql/generated";
|
||||
import { useStore } from "../store";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
|
||||
export type ImportSessionStatus =
|
||||
| "idle" // No import in progress
|
||||
| "running" // Import actively processing
|
||||
| "completed" // Import finished successfully
|
||||
| "failed" // Import finished with errors
|
||||
| "unknown"; // Unable to determine status
|
||||
|
||||
export interface ImportSessionState {
|
||||
status: ImportSessionStatus;
|
||||
sessionId: string | null;
|
||||
progress: number; // 0-100
|
||||
stats: {
|
||||
filesQueued: number;
|
||||
filesProcessed: number;
|
||||
filesSucceeded: number;
|
||||
filesFailed: number;
|
||||
} | null;
|
||||
isComplete: boolean;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom hook to definitively determine import session completion status
|
||||
*
|
||||
* Uses Socket.IO events to trigger GraphQL refetches:
|
||||
* - IMPORT_SESSION_STARTED: New import started
|
||||
* - IMPORT_SESSION_UPDATED: Progress update
|
||||
* - IMPORT_SESSION_COMPLETED: Import finished
|
||||
* - LS_IMPORT_QUEUE_DRAINED: All jobs processed
|
||||
*
|
||||
* A session is considered DEFINITIVELY COMPLETE when:
|
||||
* - session.status === "completed" OR session.status === "failed"
|
||||
* - OR LS_IMPORT_QUEUE_DRAINED event is received AND no active session exists
|
||||
* - OR IMPORT_SESSION_COMPLETED event is received
|
||||
*
|
||||
* NO POLLING - relies entirely on Socket.IO events for real-time updates
|
||||
*/
|
||||
export const useImportSessionStatus = (): ImportSessionState => {
|
||||
|
||||
const [sessionState, setSessionState] = useState<ImportSessionState>({
|
||||
status: "unknown",
|
||||
sessionId: null,
|
||||
progress: 0,
|
||||
stats: null,
|
||||
isComplete: false,
|
||||
isActive: false,
|
||||
});
|
||||
|
||||
const { getSocket } = useStore(
|
||||
useShallow((state) => ({
|
||||
getSocket: state.getSocket,
|
||||
}))
|
||||
);
|
||||
|
||||
// Track if we've received completion events
|
||||
const completionEventReceived = useRef(false);
|
||||
const queueDrainedEventReceived = useRef(false);
|
||||
|
||||
// Query active import session - NO POLLING, only refetch on Socket.IO events
|
||||
const { data: sessionData, refetch } = useGetActiveImportSessionQuery(
|
||||
{},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
refetchInterval: false, // NO POLLING
|
||||
}
|
||||
);
|
||||
|
||||
const session = sessionData?.getActiveImportSession;
|
||||
|
||||
/**
|
||||
* Determine definitive completion status
|
||||
*/
|
||||
const determineStatus = useCallback((): ImportSessionState => {
|
||||
// Case 1: No session exists
|
||||
if (!session) {
|
||||
// If we received completion events, mark as completed
|
||||
if (completionEventReceived.current || queueDrainedEventReceived.current) {
|
||||
return {
|
||||
status: "completed",
|
||||
sessionId: null,
|
||||
progress: 100,
|
||||
stats: null,
|
||||
isComplete: true,
|
||||
isActive: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Otherwise, system is idle
|
||||
return {
|
||||
status: "idle",
|
||||
sessionId: null,
|
||||
progress: 0,
|
||||
stats: null,
|
||||
isComplete: false,
|
||||
isActive: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Case 2: Session exists - check its status field
|
||||
const { status, sessionId, stats } = session;
|
||||
|
||||
// Calculate progress
|
||||
const progress = stats.filesQueued > 0
|
||||
? Math.min(100, Math.round((stats.filesSucceeded / stats.filesQueued) * 100))
|
||||
: 0;
|
||||
|
||||
// Detect stuck sessions: status="running" but all files processed
|
||||
const isStuckOrComplete =
|
||||
status === "running" &&
|
||||
stats.filesQueued > 0 &&
|
||||
stats.filesProcessed >= stats.filesQueued;
|
||||
|
||||
// DEFINITIVE COMPLETION: Check status field or stuck session
|
||||
if (status === "completed" || isStuckOrComplete) {
|
||||
completionEventReceived.current = true;
|
||||
return {
|
||||
status: "completed",
|
||||
sessionId,
|
||||
progress: 100,
|
||||
stats: {
|
||||
filesQueued: stats.filesQueued,
|
||||
filesProcessed: stats.filesProcessed,
|
||||
filesSucceeded: stats.filesSucceeded,
|
||||
filesFailed: stats.filesFailed,
|
||||
},
|
||||
isComplete: true,
|
||||
isActive: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (status === "failed") {
|
||||
completionEventReceived.current = true;
|
||||
return {
|
||||
status: "failed",
|
||||
sessionId,
|
||||
progress,
|
||||
stats: {
|
||||
filesQueued: stats.filesQueued,
|
||||
filesProcessed: stats.filesProcessed,
|
||||
filesSucceeded: stats.filesSucceeded,
|
||||
filesFailed: stats.filesFailed,
|
||||
},
|
||||
isComplete: true,
|
||||
isActive: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Case 3: Check if session is actually running/active
|
||||
if (status === "running" || status === "active" || status === "processing") {
|
||||
// Check if there's actual progress happening
|
||||
const hasProgress = stats.filesProcessed > 0 || stats.filesSucceeded > 0;
|
||||
const hasQueuedWork = stats.filesQueued > 0 && stats.filesProcessed < stats.filesQueued;
|
||||
|
||||
// Only treat as active if there's progress OR it just started
|
||||
if (hasProgress && hasQueuedWork) {
|
||||
return {
|
||||
status: "running",
|
||||
sessionId,
|
||||
progress,
|
||||
stats: {
|
||||
filesQueued: stats.filesQueued,
|
||||
filesProcessed: stats.filesProcessed,
|
||||
filesSucceeded: stats.filesSucceeded,
|
||||
filesFailed: stats.filesFailed,
|
||||
},
|
||||
isComplete: false,
|
||||
isActive: true,
|
||||
};
|
||||
} else {
|
||||
// Session says "running" but no progress - likely stuck/stale
|
||||
console.warn(`[useImportSessionStatus] Session "${sessionId}" appears stuck (status: "${status}", processed: ${stats.filesProcessed}, succeeded: ${stats.filesSucceeded}, queued: ${stats.filesQueued}) - treating as idle`);
|
||||
return {
|
||||
status: "idle",
|
||||
sessionId: null,
|
||||
progress: 0,
|
||||
stats: null,
|
||||
isComplete: false,
|
||||
isActive: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Case 4: Session exists but has unknown/other status - treat as idle
|
||||
console.warn(`[useImportSessionStatus] Unknown session status: "${status}"`);
|
||||
return {
|
||||
status: "idle",
|
||||
sessionId: null,
|
||||
progress: 0,
|
||||
stats: null,
|
||||
isComplete: false,
|
||||
isActive: false,
|
||||
};
|
||||
}, [session]);
|
||||
|
||||
/**
|
||||
* Initial fetch on mount
|
||||
*/
|
||||
useEffect(() => {
|
||||
console.log("[useImportSessionStatus] Initial mount - fetching session");
|
||||
refetch();
|
||||
}, [refetch]);
|
||||
|
||||
/**
|
||||
* Update state whenever session data changes
|
||||
*/
|
||||
useEffect(() => {
|
||||
const newState = determineStatus();
|
||||
setSessionState(newState);
|
||||
|
||||
// Log status changes for debugging
|
||||
console.log("[useImportSessionStatus] Status determined:", {
|
||||
status: newState.status,
|
||||
sessionId: newState.sessionId,
|
||||
progress: newState.progress,
|
||||
isComplete: newState.isComplete,
|
||||
isActive: newState.isActive,
|
||||
stats: newState.stats,
|
||||
rawSession: session,
|
||||
});
|
||||
}, [determineStatus, session]);
|
||||
|
||||
/**
|
||||
* Listen to Socket.IO events for real-time completion detection
|
||||
*/
|
||||
useEffect(() => {
|
||||
const socket = getSocket("/");
|
||||
|
||||
const handleSessionCompleted = () => {
|
||||
console.log("[useImportSessionStatus] IMPORT_SESSION_COMPLETED event received");
|
||||
completionEventReceived.current = true;
|
||||
refetch(); // Immediately refetch to get final status
|
||||
};
|
||||
|
||||
const handleQueueDrained = () => {
|
||||
console.log("[useImportSessionStatus] LS_IMPORT_QUEUE_DRAINED event received");
|
||||
queueDrainedEventReceived.current = true;
|
||||
refetch(); // Immediately refetch to confirm no active session
|
||||
};
|
||||
|
||||
const handleSessionStarted = () => {
|
||||
console.log("[useImportSessionStatus] IMPORT_SESSION_STARTED event received");
|
||||
// Reset completion flags when new session starts
|
||||
completionEventReceived.current = false;
|
||||
queueDrainedEventReceived.current = false;
|
||||
refetch();
|
||||
};
|
||||
|
||||
const handleSessionUpdated = () => {
|
||||
console.log("[useImportSessionStatus] IMPORT_SESSION_UPDATED event received");
|
||||
refetch();
|
||||
};
|
||||
|
||||
// Listen to completion events
|
||||
socket.on("IMPORT_SESSION_COMPLETED", handleSessionCompleted);
|
||||
socket.on("LS_IMPORT_QUEUE_DRAINED", handleQueueDrained);
|
||||
socket.on("IMPORT_SESSION_STARTED", handleSessionStarted);
|
||||
socket.on("IMPORT_SESSION_UPDATED", handleSessionUpdated);
|
||||
|
||||
return () => {
|
||||
socket.off("IMPORT_SESSION_COMPLETED", handleSessionCompleted);
|
||||
socket.off("LS_IMPORT_QUEUE_DRAINED", handleQueueDrained);
|
||||
socket.off("IMPORT_SESSION_STARTED", handleSessionStarted);
|
||||
socket.off("IMPORT_SESSION_UPDATED", handleSessionUpdated);
|
||||
};
|
||||
}, [getSocket, refetch]);
|
||||
|
||||
return sessionState;
|
||||
};
|
||||
Reference in New Issue
Block a user