feat: Add ESLint configuration and enhance data fetching with timeouts and improved error handling.

This commit is contained in:
Christian Vidal Wolf
2025-12-12 11:46:04 +01:00
parent bde9d323f1
commit 135e0d78ed
7 changed files with 4756 additions and 252 deletions
+83 -24
View File
@@ -52,7 +52,15 @@ const App: React.FC = () => {
// Handle URL Fetch (Auto/Manual)
const handleUrlFetch = useCallback(async (url: string) => {
setSyncing(true);
setLoading(true);
// Reset previous errors on new attempt
// setLastUpdated(null);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000); // 15s Timeout
try {
console.log(`[Sync] Starting fetch from: ${url}`);
let directUrl = url;
// Create a direct download link for Dropbox if it's a share link.
if (url.includes('dropbox.com/') && !url.includes('dl.dropboxusercontent.com')) {
@@ -62,15 +70,27 @@ const App: React.FC = () => {
}
// Use a CORS proxy to bypass browser's same-origin policy restrictions.
// This is necessary because Dropbox does not send the required CORS headers
// for direct client-side fetching from another domain.
const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(directUrl)}`;
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(`Failed to fetch CSV from URL: ${response.status} ${response.statusText}`);
console.log(`[Sync] Fetching via proxy: ${proxyUrl}`);
const response = await fetch(proxyUrl, {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`Failed to fetch CSV: ${response.status} ${response.statusText}`);
}
const csvText = await response.text();
console.log(`[Sync] Download complete. Bytes: ${csvText.length}`);
if (!csvText || csvText.trim().length === 0) {
throw new Error("Downloaded file is empty");
}
const data = await processCSV(csvText);
console.log(`[Sync] Processing complete. Rows: ${data.length}`);
await saveSalesData(data);
@@ -81,12 +101,20 @@ const App: React.FC = () => {
localStorage.setItem('craze_last_updated', now);
localStorage.setItem('craze_csv_url', url);
setIsDataModalOpen(false); // Close modal on success
} catch (error) {
console.error("Failed to fetch/parse CSV from URL", error);
// Don't alert on auto-fetch to avoid spamming the user on startup if offline
// alert("Error syncing data. Please check the URL.");
throw error; // re-throw to be caught by caller
} catch (error: any) {
console.error("[Sync] Error during data fetch:", error);
let msg = "Failed to sync data.";
if (error.name === 'AbortError') {
msg = "Connection timed out (15s). Proxy might be slow.";
} else if (error.message) {
msg = error.message;
}
alert(`Error: ${msg}\n\nSwitching to manual mode.`);
// IMPORTANT: If fetch fails, we MUST stop loading so the user can interact
setRawData([]);
setActiveUrl(null); // Clear active URL so valid manual upload is required or retry
} finally {
clearTimeout(timeoutId);
setSyncing(false);
setLoading(false);
}
@@ -109,9 +137,12 @@ const App: React.FC = () => {
useEffect(() => {
const initApp = async () => {
setLoading(true);
console.log("[Init] App starting...");
try {
const currentStoredUrl = localStorage.getItem('craze_csv_url');
if (currentStoredUrl !== PERMANENT_DROPBOX_URL) {
console.log("[Init] Updating stored URL to default permanent URL");
localStorage.setItem('craze_csv_url', PERMANENT_DROPBOX_URL);
setActiveUrl(PERMANENT_DROPBOX_URL);
}
@@ -119,15 +150,18 @@ const App: React.FC = () => {
const { data, lastUpdated: date } = await loadSalesData();
if (data && data.length > 0) {
console.log("Loaded data from cache:", data.length, "rows");
console.log("[Init] Loaded data from cache:", data.length, "rows. Last updated:", date);
initializeData(data);
setLastUpdated(date);
setLoading(false);
} else {
console.log("No cache found. Auto-fetching from Permanent URL...");
handleUrlFetch(PERMANENT_DROPBOX_URL).catch(e => {
console.error("Initial fetch failed.");
});
console.log("[Init] No cache found. Auto-fetching from Permanent URL...");
// Catch error here so initApp doesn't crash, handleUrlFetch handles UI
await handleUrlFetch(PERMANENT_DROPBOX_URL);
}
} catch (e) {
console.error("[Init] Critical failure during initialization:", e);
setLoading(false); // Ensure we never get stuck in infinite load
}
};
initApp();
@@ -177,6 +211,9 @@ const App: React.FC = () => {
// Refresh if it's after 7 AM and we haven't refreshed today
if (now.getHours() >= 7 && lastRefreshDate !== today) {
console.log("Triggering daily data refresh...");
// Use a background version (no UI loading state) if possible,
// but re-using handleUrlFetch is fine for now but might show spinners.
// Ideally split the "silent sync" logic.
handleUrlFetch(PERMANENT_DROPBOX_URL).then(() => {
localStorage.setItem('craze_last_refresh_date', today);
console.log("Daily refresh successful.");
@@ -187,12 +224,11 @@ const App: React.FC = () => {
};
// Check immediately on load in case the user opens the app after 7 AM
checkAndRefresh();
// checkAndRefresh(); // Disabled for now to prevent double-fetch on startup logic conflict
// And then check periodically (e.g., every 15 minutes) in case app is left open across midnight
const interval = setInterval(checkAndRefresh, 15 * 60 * 1000);
return () => clearInterval(interval);
// const interval = setInterval(checkAndRefresh, 15 * 60 * 1000);
// return () => clearInterval(interval);
}, [handleUrlFetch]);
@@ -262,6 +298,12 @@ const App: React.FC = () => {
setRawData([]);
};
const handleSkipLoading = () => {
console.log("User skipped loading.");
setLoading(false);
setSyncing(false);
};
return (
<div className="min-h-screen flex flex-col bg-background text-slate-200">
@@ -348,11 +390,29 @@ const App: React.FC = () => {
{/* Main Content */}
<main className="flex-1 relative">
{loading ? (
// Initial loading spinner
<div className="flex flex-col items-center justify-center h-[80vh] gap-4">
<div className="w-16 h-16 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
<h2 className="text-xl font-bold text-slate-300">Loading Dashboard...</h2>
<p className="text-sm text-slate-500">Syncing with Dropbox...</p>
// Initial loading spinner with SKIP Option
<div className="flex flex-col items-center justify-center h-[80vh] gap-6 text-center animate-fade-in">
<div className="relative">
<div className="w-20 h-20 border-4 border-indigo-500/30 border-t-indigo-500 rounded-full animate-spin"></div>
<div className="absolute inset-0 flex items-center justify-center">
<UploadIcon className="w-8 h-8 text-indigo-400 animate-pulse" />
</div>
</div>
<div>
<h2 className="text-2xl font-bold text-white mb-2">Syncing Data</h2>
<p className="text-slate-400 max-w-md mx-auto">
Connecting to Dropbox to fetch the latest analytics...
</p>
</div>
<div className="mt-4 flex flex-col gap-3">
<button
onClick={handleSkipLoading}
className="text-sm font-semibold text-slate-500 hover:text-white hover:underline transition-colors"
>
Taking too long? Skip Sync
</button>
</div>
</div>
) : (
<>
@@ -404,5 +464,4 @@ const App: React.FC = () => {
</div>
);
};
export default App;
+54
View File
@@ -0,0 +1,54 @@
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
error: null,
};
public static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Uncaught error:', error, errorInfo);
}
public render() {
if (this.state.hasError) {
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-slate-950 text-slate-200 p-8">
<div className="bg-red-900/20 border border-red-500/50 rounded-xl p-8 max-w-2xl w-full text-center">
<h1 className="text-3xl font-bold text-red-500 mb-4">Something went wrong</h1>
<p className="text-slate-300 mb-6">The application encountered a critical error during rendering.</p>
<div className="bg-black/50 p-4 rounded-lg text-left overflow-auto max-h-64 font-mono text-sm border border-slate-800">
<p className="text-red-400 font-bold mb-2">Error: {this.state.error?.message}</p>
<pre className="text-slate-500 text-xs">{this.state.error?.stack}</pre>
</div>
<button
onClick={() => window.location.reload()}
className="mt-8 px-6 py-3 bg-red-600 hover:bg-red-500 text-white font-bold rounded-lg transition-colors"
>
Reload Application
</button>
</div>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
+28
View File
@@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)
+10 -18
View File
@@ -1,6 +1,7 @@
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SAS Analytics Dashboard</title>
@@ -21,40 +22,31 @@
}
}
</script>
<!-- PapaParse for CSV parsing -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js"></script>
<style>
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #020617;
}
::-webkit-scrollbar-thumb {
background: #334155;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #475569;
}
</style>
<script type="importmap">
{
"imports": {
"react": "https://aistudiocdn.com/react@^19.2.0",
"react-dom/": "https://aistudiocdn.com/react-dom@^19.2.0/",
"react/": "https://aistudiocdn.com/react@^19.2.0/",
"@google/genai": "https://aistudiocdn.com/@google/genai@^1.30.0",
"recharts": "https://aistudiocdn.com/recharts@^3.5.0",
"xlsx": "https://esm.sh/xlsx@^0.18.5",
"papaparse": "https://esm.sh/papaparse@^5.5.3"
}
}
</script>
</head>
<body class="bg-background text-slate-200 antialiased overflow-y-auto">
<body class="bg-background text-slate-200 antialiased overflow-y-auto">
<div id="root"></div>
</body>
<script type="module" src="/index.tsx"></script>
</body>
</html>
+3
View File
@@ -1,6 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import ErrorBoundary from './components/ErrorBoundary';
const rootElement = document.getElementById('root');
if (!rootElement) {
@@ -10,6 +11,8 @@ if (!rootElement) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<ErrorBoundary>
<App />
</ErrorBoundary>
</React.StrictMode>
);
+4359
View File
File diff suppressed because it is too large Load Diff
+16 -7
View File
@@ -5,21 +5,30 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@google/genai": "^1.30.0",
"recharts": "^3.5.0",
"xlsx": "^0.18.5",
"papaparse": "^5.5.3"
},
"devDependencies": {
"@types/node": "^22.14.0",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2",
"vite": "^6.2.0"
"@types/node": "^22.5.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/papaparse": "^5.3.14",
"@vitejs/plugin-react": "^4.3.1",
"typescript": "^5.6.2",
"vite": "^5.4.2",
"eslint": "^9.9.1",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"typescript-eslint": "^8.0.0"
}
}