Jaguar_Project / frontend /src /components /DebugDashboard.js
xenecode's picture
Claude Opus 5.5
Translate frontend and backend text to English
6c68d01
Raw History Blame Contribute Delete
70 kB
import React, { useEffect, useState, useMemo, useRef } from "react"; import { apiService } from "../services/api.service"; import StatusCard from "./StatusCard"; import FeatureChart from "./FeatureChart"; import FileDownload from 'js-file-download'; import Button from "../components/Button"; import { ReactComponent as vertical } from '../vertical.svg'; import { ReactComponent as horizontal } from '../horizontal.svg'; import { ReactComponent as small } from '../small.svg'; // Shared classes for the dark industrial theme const BTN = 'inline-flex min-h-[44px] items-center justify-center gap-2 border-2 px-4 text-sm font-semibold uppercase tracking-[0.08em] ' + 'select-none touch-manipulation transition active:translate-y-px ' + 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-hmi-accent'; const BTN_SECONDARY = `${BTN} border-hmi-line bg-hmi-raised text-hmi-text [@media(hover:hover)]:hover:border-hmi-muted`; const segmentClass = (active) => `${BTN} ${active ? 'border-hmi-accent bg-hmi-accent text-hmi-bg' : 'border-hmi-line bg-transparent text-hmi-muted [@media(hover:hover)]:hover:text-hmi-text'}`; const FIELD = 'block min-h-[44px] w-full border border-hmi-line bg-hmi-bg px-3 text-hmi-text ' + 'focus:border-hmi-accent focus:outline-none'; const LABEL = 'mb-1.5 block text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted'; const SECTION_TITLE = 'text-sm font-semibold uppercase tracking-[0.14em] text-hmi-text'; const SMALL_BTN = 'min-h-[36px] border px-3 text-xs font-semibold uppercase tracking-[0.08em] transition active:translate-y-px'; const rateTone = (rate) => (rate >= 80 ? 'ok' : rate >= 50 ? 'warn' : 'err'); const RATE_BG = { ok: 'bg-hmi-ok', warn: 'bg-hmi-warn', err: 'bg-hmi-err' }; const DebugDashboard = () => { const [latestScan, setLatestScan] = useState(null); const [svgType, setSvgType] = useState("vertical"); const [loading, setLoading] = useState(true); const [filesLoading, setFilesLoading] = useState(true); const [error, setError] = useState(null); const [warning, setWarning] = useState(null); const [expandedIterations, setExpandedIterations] = useState({}); const [selectedFeature, setSelectedFeature] = useState(""); const [searchQuery, setSearchQuery] = useState(""); const [filterStatus, setFilterStatus] = useState("all"); const [showResults, setShowResults] = useState(false); const [selectedFile, setSelectedFile] = useState(""); const [availableFiles, setAvailableFiles] = useState([]); const [index, setIndex] = useState(0); // New state for historical data functionality const [dataMode, setDataMode] = useState("latest"); // "latest" or "historical" const [availableDates, setAvailableDates] = useState([]); const [startDate, setStartDate] = useState(""); const [endDate, setEndDate] = useState(""); const [datesLoading, setDatesLoading] = useState(false); const resultsRef = useRef(null); // On narrow screens the results panel stacks below; make it visible when opened useEffect(() => { if (showResults && !window.matchMedia('(min-width: 1280px)').matches) { resultsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }, [showResults]); // Extract feature list for dropdown const featureList = useMemo(() => { return Array.from(new Set( latestScan?.scan_results?.flatMap(iter => iter.features?.filter(f => !["Index", "OK", "Processing Time (s)"].includes(f.name)) .map(f => f.name) ) || [] )); }, [latestScan]); const arr1 = [ "Feature6 (L248)", "Feature8 (L79.73)", "Feature7 (L42)", "Feature10 (R2-35)", "Feature12 (88.6)", "Feature9 (R1-50)", "Feature14 (81.5)" ]; const arr2 = [ "Feature15 (L23.4)", "Feature17 (2C)", "Feature4 (25mm/2)", "Feature11 (3mm)", "Feature16 (L17.2)", "Feature3 (23.1)", "Feature13 (10.6)" ]; // Initialize default dates (yesterday) useEffect(() => { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const yesterdayStr = yesterday.toISOString().split('T')[0]; setStartDate(yesterdayStr); setEndDate(yesterdayStr); }, []); // Fetch available dates when component mounts useEffect(() => { fetchAvailableDates(); }, []); useEffect(() => { // Fetch available files for latest mode const fetchAvailableFiles = async () => { try { setFilesLoading(true); const response = await apiService.getLatestScan('scan_output.json'); if (response.available_files) { setAvailableFiles(response.available_files); setSelectedFile(response.available_files[0]?.name || 'scan_output.json'); } else { setError('No available file found'); } setFilesLoading(false); } catch (err) { setError('Could not load file list'); setFilesLoading(false); } }; if (dataMode === "latest") { fetchAvailableFiles(); } }, [dataMode]); useEffect(() => { if (dataMode === "latest" && selectedFile) { fetchLatestScan(); } }, [selectedFile, dataMode]); const submitDateRange = () => { if (dataMode === "historical" && startDate && endDate) { fetchHistoricalScan(); } }; const fetchAvailableDates = async () => { try { setDatesLoading(true); const response = await apiService.getAvailableDates(); setAvailableDates(response.available_dates || []); setDatesLoading(false); } catch (err) { setWarning('Could not load date list for historical data'); setDatesLoading(false); } }; const fetchLatestScan = async () => { try { setLoading(true); setError(null); setWarning(null); setSearchQuery(""); // Reset search query setFilterStatus("all"); // Reset filter status setExpandedIterations({}); // Reset expanded iterations const data = await apiService.getLatestScan(selectedFile); // Handle error response if (data.message && data.available_files) { setError(data.message); setAvailableFiles(data.available_files); setLoading(false); return; } // Convert status.ok to boolean explicitly const correctedData = { ...data, scan_results: data?.scan_results?.map(iteration => ({ ...iteration, features: iteration?.features?.map(feature => ({ ...feature, tolerance_check: { ...feature.tolerance_check, within_tolerance: feature.tolerance_check?.within_tolerance === true || feature.tolerance_check?.within_tolerance === "true" } })) || [], status: { ...iteration.status, ok: iteration.status?.ok === true || iteration.status?.ok === "true" } })) || [] }; setLatestScan(correctedData); // Initialize first iteration as expanded if (correctedData?.scan_results) { const initialExpandState = {}; correctedData.scan_results.forEach((_, index) => { initialExpandState[index] = index === 0; }); setExpandedIterations(initialExpandState); } setLoading(false); } catch (error) { setError('Could not load scan data'); setLoading(false); } }; const fetchHistoricalScan = async () => { try { setLoading(true); setError(null); setWarning(null); setSearchQuery(""); // Reset search query setFilterStatus("all"); // Reset filter status setExpandedIterations({}); // Reset expanded iterations const data = await apiService.getHistoricalScan(startDate, endDate); // Handle case where no data found if (data.message && data.data && data.data.length === 0) { setWarning(`No data found in range ${startDate} – ${endDate}`); setLatestScan(null); setLoading(false); return; } // Convert status.ok to boolean explicitly const correctedData = { ...data, scan_results: data?.scan_results?.map(iteration => ({ ...iteration, features: iteration?.features?.map(feature => ({ ...feature, tolerance_check: { ...feature.tolerance_check, within_tolerance: feature.tolerance_check?.within_tolerance === true || feature.tolerance_check?.within_tolerance === "true" } })) || [], status: { ...iteration.status, ok: iteration.status?.ok === true || iteration.status?.ok === "true" } })) || [] }; setLatestScan(correctedData); // Initialize first iteration as expanded if (correctedData?.scan_results) { const initialExpandState = {}; correctedData.scan_results.forEach((_, index) => { initialExpandState[index] = index === 0; }); setExpandedIterations(initialExpandState); } setLoading(false); } catch (error) { setError('Could not load historical scan data'); console.error('Error fetching historical scan:', error); setLoading(false); } }; // Filter iterations based on search query and status filter const filteredIterations = useMemo(() => { if (!latestScan?.scan_results) return []; return latestScan.scan_results.filter(iteration => { if (filterStatus === "pass" && !iteration.status?.ok) return false; if (filterStatus === "fail" && iteration.status?.ok) return false; if (!searchQuery) return true; const query = searchQuery.toLowerCase(); const indexFeature = iteration.features?.find(f => f.name.toLowerCase() === "index"); const indexMatch = indexFeature && String(indexFeature.value).toLowerCase().includes(query); const okFeature = iteration.features?.find(f => f.name.toLowerCase() === "ok"); const okMatch = okFeature && String(okFeature.value).toLowerCase().includes(query); const timeFeature = iteration.features?.find(f => f.name.toLowerCase().includes("processing time")); const timeMatch = timeFeature && String(timeFeature.value).toLowerCase().includes(query); const featureMatch = iteration.features?.some(feature => feature.name?.toLowerCase().includes(query) || String(feature.value).toLowerCase().includes(query) || Object.values(feature.tolerance_check || {}).some(val => String(val).toLowerCase().includes(query) ) ); const failureMatch = iteration.status?.failure_reasons?.some(reason => reason.toLowerCase().includes(query) ); return indexMatch || okMatch || timeMatch || featureMatch || failureMatch; }); }, [latestScan, searchQuery, filterStatus]); const downloadExcel = () => { if (dataMode === "latest") { apiService.downloadExcel(selectedFile).then((res) => { FileDownload(res.data, `${selectedFile || 'data'}.xlsx`); }); } else { // For historical data, we might need a different endpoint or approach // This depends on your backend implementation setWarning('Excel download for historical data is not yet supported'); } }; const toggleIteration = (index) => { setIndex((index) => latestScan?.scan_results[index]?.features?.find(f => f.name.toLowerCase() === "index") || 0); setExpandedIterations(prev => ({ ...prev, [index]: !prev[index] })); }; const expandAll = () => { const allExpanded = {}; filteredIterations.forEach((_, index) => { allExpanded[index] = true; }); setExpandedIterations(allExpanded); }; const collapseAll = () => { const allCollapsed = {}; filteredIterations.forEach((_, index) => { allCollapsed[index] = false; }); setExpandedIterations(allCollapsed); }; const calculateStats = () => { if (!latestScan?.scan_results) { return { total: 0, passed: 0, failed: 0, failureReasons: {}, passRate: 0 }; } const stats = { total: latestScan.scan_results.length, passed: 0, failed: 0, failureReasons: {} }; latestScan.scan_results.forEach(iteration => { if (iteration.status.ok) { stats.passed++; } else { stats.failed++; if (iteration.status.failure_reasons) { iteration.status.failure_reasons.forEach(reason => { const featureMatch = reason.match(/^(.*?)\s+out of tolerance/); const featureName = featureMatch ? featureMatch[1] : reason; stats.failureReasons[featureName] = (stats.failureReasons[featureName] || 0) + 1; }); } } }); stats.passRate = stats.total > 0 ? (stats.passed / stats.total * 100) : 0; return stats; }; const stats = calculateStats(); if (filesLoading || datesLoading) { return ( <div className="flex min-h-[calc(100dvh-3rem)] items-center justify-center bg-hmi-bg font-hmi"> <div className="flex flex-col items-center gap-4"> <div className="h-10 w-10 animate-spin border-4 border-hmi-line border-t-hmi-accent" aria-hidden="true" /> <span className="text-sm font-semibold uppercase tracking-[0.14em] text-hmi-muted">Loading data</span> </div> </div> ); } if (error) { return ( <div className="flex min-h-[calc(100dvh-3rem)] items-center justify-center bg-hmi-bg px-4 font-hmi"> <div className="w-full max-w-lg border-2 border-hmi-err bg-hmi-panel px-6 py-6 text-center"> <div className="text-xl font-semibold text-hmi-err">{error}</div> <button type="button" className={`${BTN} mt-5 border-red-600 bg-red-600 text-white [@media(hover:hover)]:hover:bg-red-500`} onClick={() => window.location.reload()} > Retry </button> </div> </div> ); } if (warning && (!latestScan || !latestScan.scan_results || latestScan.scan_results.length === 0)) { return ( <div className="flex min-h-[calc(100dvh-3rem)] items-center justify-center bg-hmi-bg px-4 font-hmi"> <div className="w-full max-w-lg border-2 border-hmi-warn bg-hmi-panel px-6 py-6 text-center"> <div className="text-xl font-semibold text-hmi-warn">{warning}</div> <div className="mt-2 text-hmi-muted">Select a different date range or switch to the latest data.</div> <div className="mt-5 flex justify-center gap-2"> <button type="button" className={`${BTN} border-hmi-warn bg-transparent text-hmi-warn`} onClick={() => setDataMode("latest")} > Switch to latest data </button> <button type="button" className={BTN_SECONDARY} onClick={() => window.location.reload()} > Refresh </button> </div> </div> </div> ); } const TechDraw = ({ iterationIndex = 0 }) => { const svgTypes = ["vertical", "horizontal", "small"]; const svgTypeLabels = { vertical: "Vertical", horizontal: "Horizontal", small: "Small" }; // Next SVG type navigation function const getNextSvgType = (currentType) => { const currentIndex = svgTypes.indexOf(currentType); return svgTypes[(currentIndex + 1) % svgTypes.length]; }; const handleNextSvgType = () => { const nextType = getNextSvgType(svgType); setSvgType(nextType); }; let SvgObject; if (svgType === "horizontal") SvgObject = horizontal; else if (svgType === "vertical") SvgObject = vertical; else SvgObject = small; const features = latestScan?.scan_results?.find(iter => { const idxFeature = iter.features?.find(f => f.name?.toLowerCase() === "index"); return String(idxFeature?.value) === String(iterationIndex); })?.features || []; const getFeature = (idx, defaultName) => ({ name: features[idx]?.name || defaultName, value: features[idx]?.value ?? "N/A", }); const svgWidth = 822; const svgHeight = 531; // Label border colors: drawing is on a light background, labels sit in dark boxes const labelBorders = [ "#6366F1", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#06B6D4", "#84CC16", "#F97316", ]; let featureLabels; if (svgType === "horizontal") { featureLabels = [ { idx: 0, x: 225, y: 85 }, { idx: 1, x: 560, y: 10 }, { idx: 4, x: 360, y: 450 }, ]; } else if (svgType === "vertical") { featureLabels = [ { idx: 5, x: 28, y: 27 }, { idx: 6, x: 625, y: 22 }, { idx: 7, x: 373, y: 32 }, { idx: 8, x: 460, y: 265 }, { idx: 9, x: 468, y: 150 }, { idx: 11, x: 800, y: 180 }, { idx: 13, x: 840, y: 240 }, ]; } else { featureLabels = [ { idx: 10, x: 802, y: 300 }, { idx: 12, x: -30, y: 350 }, { idx: 14, x: 640, y: 30 }, { idx: 15, x: 680, y: 430 }, { idx: 16, x: 730, y: 85 }, { idx: 2, x: 50, y: 300 }, { idx: 3, x: 700, y: 280 }, ]; } const iterationIndices = latestScan?.scan_results?.map(iter => { const idxFeature = iter.features?.find(f => f.name?.toLowerCase() === "index"); return idxFeature?.value; }) || []; return ( <div className="w-full border border-hmi-line bg-hmi-bg px-4 py-4"> {/* SVG Type Buttons */} <div className="mb-4 flex items-center gap-2"> {svgTypes.map((type) => ( <button key={type} type="button" onClick={() => setSvgType(type)} aria-pressed={svgType === type} className={segmentClass(svgType === type)} > {svgTypeLabels[type]} </button> ))} </div> {/* Iteration Selector */} <div className="mb-4 flex flex-wrap gap-1.5"> {iterationIndices.map((idx) => ( <button key={idx} type="button" onClick={() => setIndex(Number(idx))} className={`min-h-[40px] min-w-[44px] border px-2 font-mono text-sm font-semibold transition active:translate-y-px ${iterationIndex === idx ? "border-hmi-accent bg-hmi-accent text-hmi-bg" : "border-hmi-line bg-hmi-panel text-hmi-text [@media(hover:hover)]:hover:border-hmi-muted" }`} > {idx} </button> ))} </div> {/* SVG Container with Arrow Navigation */} <div className="overflow-x-auto"> <div className="flex w-max items-center gap-4 px-10 py-10"> <div className="relative border border-hmi-line bg-white" style={{ width: svgWidth, height: svgHeight }}> <SvgObject style={{ width: svgWidth, height: svgHeight, display: "block" }} /> {featureLabels.map(({ idx, x, y }, i) => { const { name, value } = getFeature(idx, `feature${idx + 1}`); const border = labelBorders[idx % labelBorders.length]; return ( <div key={i} className="absolute bg-hmi-panel text-center" style={{ left: x, top: y, transform: "translate(-50%, -100%)", pointerEvents: "none", zIndex: 10, minWidth: "80px", borderColor: border, borderWidth: "2px", borderStyle: "solid" }} > <div className="px-2 py-1 text-xs font-semibold text-hmi-text"> {name} </div> <div className="px-2 pb-1 font-mono text-xs text-hmi-text"> {value} </div> <div className="absolute left-1/2 top-full h-3 w-px -translate-x-1/2" style={{ backgroundColor: border }} ></div> <div className="absolute left-1/2 top-full -translate-x-1/2 translate-y-2"> <div className="h-2 w-2 -translate-y-1 rotate-45" style={{ backgroundColor: border }} ></div> </div> </div> ); })} </div> {/* Right Arrow Navigation Button */} <button type="button" onClick={handleNextSvgType} className="flex h-12 w-12 items-center justify-center border-2 border-hmi-line bg-hmi-raised text-hmi-text transition active:translate-y-px [@media(hover:hover)]:hover:border-hmi-accent" title={`Next: ${svgTypeLabels[getNextSvgType(svgType)]}`} aria-label={`Next drawing: ${svgTypeLabels[getNextSvgType(svgType)]}`} > <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter" > <polyline points="9,18 15,12 9,6"></polyline> </svg> </button> </div> </div> </div> ); }; const renderEnhancedSummary = () => { const tone = rateTone(stats.passRate); return ( <section className="mb-5 border border-hmi-line bg-hmi-panel"> <div className="flex items-center justify-between gap-4 border-b border-hmi-line px-4 py-2.5"> <span className={SECTION_TITLE}>Scan summary</span> <span className="font-mono text-xs text-hmi-muted"> {dataMode === "historical" && startDate && endDate ? `${startDate} – ${endDate}` : new Date().toLocaleString('en-US') } </span> </div> <div className="px-4 py-4"> {warning && ( <div role="status" className="mb-4 flex items-start gap-3 border border-hmi-warn/60 bg-hmi-warn/10 px-3 py-2.5 text-sm text-hmi-warn"> <span aria-hidden="true">⚠</span> <span>{warning}</span> </div> )} <div className="mb-4 grid grid-cols-2 gap-2 md:grid-cols-4"> <StatusCard title="Total iterations" value={stats.total} /> <StatusCard title="Passed" value={stats.passed} tone="ok" /> <StatusCard title="Failed" value={stats.failed} tone={stats.failed > 0 ? 'err' : 'neutral'} /> <StatusCard title="Pass rate" value={`${stats.passRate.toFixed(1)}%`} tone={tone} /> </div> <div> <div className="mb-1.5 flex justify-between text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted"> <span>Pass rate</span> <span className="font-mono">{stats.passRate.toFixed(1)}%</span> </div> <div className="h-3 border border-hmi-line bg-hmi-bg"> <div className={`h-full ${RATE_BG[tone]}`} style={{ width: `${Math.min(100, stats.passRate)}%` }} ></div> </div> </div> </div> {stats.failed > 0 && Object.keys(stats.failureReasons).length > 0 && ( <div className="border-t border-hmi-line px-4 py-4"> <div className={`${SECTION_TITLE} mb-3`}>Technical drawing</div> <TechDraw iterationIndex={index} /> <div className={`${SECTION_TITLE} mb-3 mt-6`}>Most common failure reasons</div> <div className="overflow-x-auto border border-hmi-line"> <table className="min-w-full"> <thead> <tr className="bg-hmi-raised"> <th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted">Feature</th> <th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted">Count</th> <th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted">Distribution</th> </tr> </thead> <tbody> {Object.entries(stats.failureReasons) .sort((a, b) => (b[1] / stats.total) - (a[1] / stats.total)) .map(([reason, count], idx) => { const percentage = (count / stats.total * 100).toFixed(1); return ( <tr key={idx} className="border-t border-hmi-line"> <td className="px-3"> <button type="button" onClick={() => setSvgType( arr1.includes(reason) ? "vertical" : arr2.includes(reason) ? "small" : "horizontal" ) } className="min-h-[40px] text-left font-medium text-hmi-err underline-offset-2 [@media(hover:hover)]:hover:underline" > {reason} </button> </td> <td className="px-3 py-2 font-mono">{count}</td> <td className="w-1/3 px-3 py-2"> <div className="flex items-center gap-3"> <div className="h-2.5 w-full border border-hmi-line bg-hmi-bg"> <div className="h-full bg-hmi-err" style={{ width: `${percentage}%` }}></div> </div> <span className="font-mono text-xs text-hmi-muted">{percentage}%</span> </div> </td> </tr> ); }) } </tbody> </table> </div> </div> )} </section> ); }; const renderControlPanel = () => { return ( <section className="mb-5 border border-hmi-line bg-hmi-panel px-4 py-4"> {/* Data Mode Toggle */} <div className="mb-4"> <span className={LABEL}>Data mode</span> <div className="flex gap-2"> <button type="button" aria-pressed={dataMode === "latest"} className={segmentClass(dataMode === "latest")} onClick={() => setDataMode("latest")} > Latest data </button> <button type="button" aria-pressed={dataMode === "historical"} className={segmentClass(dataMode === "historical")} onClick={() => setDataMode("historical")} > Historical data </button> </div> </div> {/* Latest Data Controls */} {dataMode === "latest" && ( <div className="mb-4"> <label htmlFor="fileSelector" className={LABEL}>Data file</label> {filesLoading ? ( <div className="flex items-center gap-2 text-hmi-muted"> <div className="h-5 w-5 animate-spin border-2 border-hmi-line border-t-hmi-accent"></div> <span>Loading files</span> </div> ) : ( <div className="flex flex-col gap-2 sm:flex-row"> <select id="fileSelector" className={FIELD} value={selectedFile} onChange={(e) => setSelectedFile(e.target.value)} > {availableFiles.map((file, index) => ( <option key={index} value={file.name}>{file.label}</option> ))} </select> <Button text="Download Excel" type="secondary" className="shrink-0" onClick={downloadExcel} /> </div> )} </div> )} {/* Historical Data Controls */} {dataMode === "historical" && ( <div className="mb-4 flex flex-col gap-4"> <div className="grid grid-cols-1 gap-4 md:grid-cols-2"> <div> <label htmlFor="startDate" className={LABEL}>Start date</label> <input type="date" id="startDate" className={FIELD} value={startDate} onChange={(e) => setStartDate(e.target.value)} /> </div> <div> <label htmlFor="endDate" className={LABEL}>End date</label> <input type="date" id="endDate" className={FIELD} value={endDate} onChange={(e) => setEndDate(e.target.value)} /> </div> </div> <div className="flex justify-start"> <Button text="Fetch range" onClick={submitDateRange} type="primary" /> </div> {availableDates.length > 0 && ( <div> <span className={LABEL}> Recorded dates ({availableDates.length}) </span> <div className="max-h-24 overflow-y-auto border border-hmi-line bg-hmi-bg px-3 py-2 font-mono text-xs text-hmi-muted"> {availableDates.slice(0, 10).join(', ')} {availableDates.length > 10 && ` … and ${availableDates.length - 10} more`} </div> </div> )} </div> )} <div className="mb-4 flex flex-col gap-4 md:flex-row"> <div className="flex-grow"> <label htmlFor="search" className={LABEL}>Search</label> <div className="relative"> <input id="search" type="text" className={`${FIELD} pl-10`} placeholder="Search feature, value, or failure reason…" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} /> <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"> <svg className="h-5 w-5 text-hmi-muted" fill="currentColor" viewBox="0 0 20 20"> <path fillRule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clipRule="evenodd" /> </svg> </div> </div> </div> <div> <label htmlFor="statusFilter" className={LABEL}>Status filter</label> <select id="statusFilter" className={FIELD} value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)} > <option value="all">All results</option> <option value="pass">Only passed</option> <option value="fail">Only failed</option> </select> </div> <div> <label htmlFor="featureSelect" className={LABEL}>Feature trend analysis</label> <select id="featureSelect" className={FIELD} value={selectedFeature} onChange={(e) => setSelectedFeature(e.target.value)} > <option value="">Select feature</option> {featureList.map((name, idx) => ( <option key={idx} value={name}>{name}</option> ))} </select> </div> </div> <div className="flex flex-wrap gap-2"> <button type="button" onClick={expandAll} className={BTN_SECONDARY}> <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path strokeLinecap="square" strokeWidth="2" d="M19 9l-7 7-7-7"></path> </svg> Expand all </button> <button type="button" onClick={collapseAll} className={BTN_SECONDARY}> <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path strokeLinecap="square" strokeWidth="2" d="M5 15l7-7 7 7"></path> </svg> Collapse all </button> <button type="button" onClick={() => setFilterStatus('fail')} className={`${BTN} border-hmi-err/60 bg-transparent text-hmi-err [@media(hover:hover)]:hover:border-hmi-err`} > <span aria-hidden="true">✕</span> Only failed </button> <button type="button" onClick={() => { setSearchQuery(""); setFilterStatus("all"); }} className={BTN_SECONDARY} > <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path strokeLinecap="square" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path> </svg> Reset filters </button> </div> </section> ); }; const renderIteration = (iterationData, index) => { const displayFeatures = iterationData.features.filter( (f) => !["Index", "OK", "Processing Time (s)"].includes(f.name) ); const processingTimeFeature = iterationData.features.find( (f) => f.name.toLowerCase().includes("processing time") ); const isExpanded = expandedIterations[index]; const hasFailed = iterationData.status.ok === false; const validFeatures = iterationData.features.filter(f => f.tolerance_check && !f.tolerance_check.error); const passedFeatures = validFeatures.filter(f => f.tolerance_check.within_tolerance === true).length; const totalFeatures = validFeatures.length; const passRate = totalFeatures > 0 ? (passedFeatures / totalFeatures) * 100 : 0; const indexFeature = iterationData.features?.find( (f) => f.name?.toLowerCase() === "index" ); // Row filters hide the table directly via the DOM (previous behavior) const filterRows = (e, predicate) => { e.stopPropagation(); const table = document.getElementById(`features-table-${index}`); table.querySelectorAll("tbody tr").forEach((row) => { row.style.display = predicate(row) ? "" : "none"; }); }; return ( <div key={index} className={`border bg-hmi-panel ${hasFailed ? "border-hmi-err/50" : "border-hmi-line"}`}> <div role="button" tabIndex={0} aria-expanded={Boolean(isExpanded)} className={`flex min-h-[56px] cursor-pointer items-center justify-between gap-3 border-l-4 px-3 py-2 transition-colors ${hasFailed ? "border-l-hmi-err" : "border-l-hmi-ok"} [@media(hover:hover)]:hover:bg-hmi-raised`} onClick={() => toggleIteration(index)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleIteration(index); } }} > <div className="flex min-w-0 items-center gap-3"> <span className="text-hmi-muted transition-transform duration-200" style={{ transform: isExpanded ? "rotate(90deg)" : "rotate(0)" }} > <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path strokeLinecap="square" strokeWidth="2" d="M9 5l7 7-7 7" /> </svg> </span> {indexFeature && ( <span className="whitespace-nowrap font-mono font-semibold"> <span className="text-hmi-muted">Index</span> {indexFeature.value} </span> )} <div className="hidden items-center gap-2 sm:flex"> <div className="h-2.5 w-24 border border-hmi-line bg-hmi-bg"> <div className={`h-full ${hasFailed ? "bg-hmi-err" : "bg-hmi-ok"}`} style={{ width: `${passRate}%` }} ></div> </div> <span className="whitespace-nowrap text-xs text-hmi-muted"> <span className="font-mono">{passedFeatures}/{totalFeatures}</span> features passed </span> </div> </div> <div className="flex shrink-0 items-center gap-3"> {processingTimeFeature && ( <span className="hidden font-mono text-sm text-hmi-muted sm:block"> {processingTimeFeature.value.toFixed(1)} s </span> )} <span className={`border px-2.5 py-1 font-mono text-xs font-bold uppercase ${hasFailed ? "border-hmi-err text-hmi-err" : "border-hmi-ok text-hmi-ok"}`} > {hasFailed ? "✕ Failed" : "✓ Passed"} </span> </div> </div> {isExpanded && ( <div className="border-t border-hmi-line"> {hasFailed && iterationData.status.failure_reasons?.length > 0 && ( <div className="border-b border-hmi-line bg-hmi-err/10 px-4 py-3"> <div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-hmi-err">Failure reasons</div> <ul className="list-disc space-y-1 pl-5 text-sm text-hmi-err"> {iterationData.status.failure_reasons.map((reason, idx) => ( <li key={idx}>{reason}</li> ))} </ul> </div> )} <div className="flex flex-wrap gap-2 border-b border-hmi-line bg-hmi-bg px-3 py-2"> <button type="button" className={`${SMALL_BTN} border-hmi-line text-hmi-text`} onClick={(e) => filterRows(e, () => true)} > All </button> <button type="button" className={`${SMALL_BTN} border-hmi-err/60 text-hmi-err`} onClick={(e) => filterRows(e, (row) => row.classList.contains("failed-feature"))} > Only failed </button> <button type="button" className={`${SMALL_BTN} border-hmi-ok/60 text-hmi-ok`} onClick={(e) => filterRows(e, (row) => row.classList.contains("passed-feature"))} > Only passed </button> </div> <div className="overflow-x-auto"> <table id={`features-table-${index}`} className="min-w-full"> <thead> <tr className="bg-hmi-raised"> <th className="w-1/4 px-4 py-2 text-left text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted"> Feature </th> <th className="w-1/4 px-4 py-2 text-left text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted"> Value </th> <th className="w-2/4 px-4 py-2 text-left text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted"> Tolerance check </th> </tr> </thead> <tbody> {displayFeatures.map((feature, featureIdx) => { const tc = feature.tolerance_check; const hasFailed = tc && !tc.error && !tc.within_tolerance; const hasPassed = tc && !tc.error && tc.within_tolerance; const tolerance = tc?.tolerance || 0; const distance = tc?.distance || 0; const utilization = tolerance > 0 ? Math.abs(distance / tolerance) * 100 : 0; return ( <tr key={featureIdx} className={`border-t border-hmi-line ${hasFailed ? "bg-hmi-err/5 failed-feature" : hasPassed ? "passed-feature" : ""}`} > <td className="px-4 py-3 font-medium"> <div className="flex items-center gap-2"> {hasFailed && ( <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center border border-hmi-err text-xs text-hmi-err"> ✕ </span> )} {hasPassed && ( <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center border border-hmi-ok text-xs text-hmi-ok"> ✓ </span> )} {feature.name} </div> </td> <td className="px-4 py-3 font-mono" style={{ color: feature.value_color?.startsWith("#") ? feature.value_color : feature.value_color ? `#${feature.value_color}` : undefined, fontWeight: hasFailed ? "bold" : "normal", }} > {typeof feature.value === "object" && feature.value !== null ? JSON.stringify(feature.value) : typeof feature.value === "number" ? feature.value.toFixed(3) : feature.value} </td> <td className="px-4 py-3"> {!tc ? ( <span className="italic text-hmi-muted">Tolerance not defined</span> ) : tc.error ? ( <span className="italic text-hmi-muted">{tc.error}</span> ) : ( <div> <div className="mb-2 grid grid-cols-2 gap-2 text-sm md:grid-cols-4"> <div> <span className="text-xs text-hmi-muted">Target</span>{" "} <span className="font-mono font-medium">{tc.target}</span> </div> <div> <span className="text-xs text-hmi-muted">Tolerance</span>{" "} <span className="font-mono font-medium">±{tc.tolerance}</span> </div> <div> <span className="text-xs text-hmi-muted">Deviation</span>{" "} <span className={`font-mono font-medium ${hasFailed ? "text-hmi-err" : "text-hmi-text"}`}> {distance.toFixed(3)} </span> </div> <div> <span className="text-xs text-hmi-muted">Remaining</span>{" "} <span className={`font-mono font-medium ${tc.tolerance_remaining < 0 ? "text-hmi-err" : tc.tolerance_remaining / tolerance < 0.2 ? "text-hmi-warn" : "text-hmi-ok" }`} > {tc.tolerance_remaining?.toFixed(3) || "N/A"} </span> </div> </div> {tolerance > 0 && ( <div> <div className="flex items-center gap-2"> <div className="relative h-3 flex-grow overflow-hidden border border-hmi-line bg-hmi-bg"> <div className="absolute inset-y-0 left-1/2 z-10 w-0.5 bg-hmi-text"></div> <div className={`absolute inset-y-0 h-full ${hasFailed ? "bg-hmi-err" : "bg-hmi-ok"}`} style={{ width: `${Math.min(100, utilization)}%`, left: "50%", transform: feature.value < tc.target ? "translateX(-100%)" : "none", }} ></div> </div> <span className={`font-mono text-xs ${hasFailed ? "text-hmi-err" : "text-hmi-ok"}`}> {utilization.toFixed(1)}% </span> </div> <div className="mt-1 flex justify-between font-mono text-xs text-hmi-muted"> <span>{(tc.target - tc.tolerance).toFixed(1)}</span> <span>{tc.target}</span> <span>{(tc.target + tc.tolerance).toFixed(1)}</span> </div> </div> )} </div> )} </td> </tr> ); })} </tbody> </table> </div> <div className="flex flex-wrap items-center gap-x-5 gap-y-1 border-t border-hmi-line bg-hmi-bg px-4 py-2 text-sm text-hmi-muted"> {processingTimeFeature && ( <div> Processing time{" "} <span className="font-mono text-hmi-text">{processingTimeFeature.value.toFixed(2)} s</span> </div> )} <div> Feature pass rate{" "} <span className="font-mono text-hmi-text"> {passedFeatures}/{totalFeatures} ({passRate.toFixed(1)}%) </span> </div> <button type="button" className="min-h-[40px] font-semibold uppercase tracking-[0.08em] text-hmi-accent [@media(hover:hover)]:hover:underline" onClick={(e) => { e.stopPropagation(); const failed = displayFeatures.find( (f) => f.tolerance_check && !f.tolerance_check.error && !f.tolerance_check.within_tolerance ); const first = displayFeatures[0]; setSelectedFeature(failed ? failed.name : first?.name); document.getElementById("feature-chart-section")?.scrollIntoView({ behavior: "smooth" }); }} > Analyze features </button> </div> </div> )} </div> ); }; const resultCount = filteredIterations?.length || 0; return ( <div className="flex min-h-[calc(100dvh-3rem)] flex-col bg-hmi-bg font-hmi text-hmi-text xl:flex-row"> {/* Side-by-side layout only on wide screens; columns got cramped on 1024px touch screens */} <div className={`w-full ${showResults ? 'pr-20 xl:w-1/2 xl:pr-4' : 'pr-20 xl:w-full'} overflow-y-auto px-4 py-4 xl:sticky xl:top-12 xl:h-[calc(100dvh-3rem)]`} > <div className="mb-5 flex items-center gap-3"> <svg className="h-5 w-5 text-hmi-accent" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" > <path strokeLinecap="square" strokeWidth="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" ></path> </svg> <span className="text-lg font-bold uppercase tracking-[0.14em]">Scan results</span> </div> {/* Results panel tab: fixed on the right edge, wide for touch */} <button type="button" onClick={() => setShowResults((prev) => !prev)} aria-expanded={showResults} aria-label={showResults ? 'Hide results' : 'Show results'} className={`fixed right-0 top-1/2 z-40 flex min-h-[160px] w-16 -translate-y-1/2 flex-col items-center justify-center gap-3 border-2 border-r-0 py-4 transition-colors touch-manipulation focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-hmi-accent ${showResults ? 'border-hmi-accent bg-hmi-accent text-hmi-bg' : 'border-hmi-line bg-hmi-panel text-hmi-text [@media(hover:hover)]:hover:border-hmi-accent' }`} > <svg className={`h-5 w-5 transition-transform duration-300 ${showResults ? 'rotate-180' : 'rotate-0'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2.5" aria-hidden="true" > <path strokeLinecap="square" d="M15 19l-7-7 7-7" /> </svg> <span className="rotate-180 text-xs font-semibold uppercase tracking-[0.14em] [writing-mode:vertical-rl]"> Results </span> <span className={`min-w-[28px] px-1.5 py-0.5 text-center font-mono text-xs font-bold ${showResults ? 'bg-hmi-bg text-hmi-accent' : resultCount > 0 ? 'bg-hmi-accent text-hmi-bg' : 'bg-hmi-raised text-hmi-muted' }`} > {resultCount > 99 ? '99+' : resultCount} </span> </button> {renderEnhancedSummary()} {renderControlPanel()} <div id="feature-chart-section"> {selectedFeature && ( <FeatureChart data={latestScan.scan_results} selectedFeature={selectedFeature} /> )} </div> </div> {showResults && ( <div ref={resultsRef} className="w-full scroll-mt-12 overflow-y-auto border-t border-hmi-line bg-hmi-bg py-4 pl-4 pr-20 xl:h-[calc(100dvh-3rem)] xl:w-1/2 xl:border-l xl:border-t-0" > <div className="mb-4 flex items-center justify-between gap-3 border border-hmi-line bg-hmi-panel px-4 py-2"> <div className="flex items-center gap-3 text-sm"> <span className="h-2.5 w-2.5 bg-hmi-ok" aria-hidden="true"></span> <span> <span className="font-mono font-semibold">{resultCount}</span> <span className="text-hmi-muted"> / </span> <span className="font-mono">{latestScan?.scan_results?.length ?? 0}</span> <span className="text-hmi-muted"> iterations shown</span> </span> </div> <button type="button" onClick={() => setShowResults(false)} className="flex h-11 w-11 items-center justify-center border-2 border-hmi-line text-hmi-text transition active:translate-y-px [@media(hover:hover)]:hover:border-hmi-muted" aria-label="Close results" > <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2" aria-hidden="true" > <path strokeLinecap="square" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> <div className="flex flex-col gap-3"> {filteredIterations.length > 0 ? ( filteredIterations.slice().reverse().map((iteration, idx) => ( <div key={idx} className="w-full"> {renderIteration(iteration, idx)} </div> )) ) : ( <div className="border border-hmi-line bg-hmi-panel px-8 py-8 text-center"> <div className="text-xl font-semibold text-hmi-text"> No results match the filters </div> <div className="mt-2 text-hmi-muted"> Try changing your search criteria </div> </div> )} </div> </div> )} </div> ); }; export default DebugDashboard;
import React, { useEffect, useState, useMemo, useRef } from "react";
import { apiService } from "../services/api.service";
import StatusCard from "./StatusCard";
import FeatureChart from "./FeatureChart";
import FileDownload from 'js-file-download';
import Button from "../components/Button";
import { ReactComponent as vertical } from '../vertical.svg';
import { ReactComponent as horizontal } from '../horizontal.svg';
import { ReactComponent as small } from '../small.svg';
// Shared classes for the dark industrial theme
const BTN =
'inline-flex min-h-[44px] items-center justify-center gap-2 border-2 px-4 text-sm font-semibold uppercase tracking-[0.08em] ' +
'select-none touch-manipulation transition active:translate-y-px ' +
'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-hmi-accent';
const BTN_SECONDARY = `${BTN} border-hmi-line bg-hmi-raised text-hmi-text [@media(hover:hover)]:hover:border-hmi-muted`;
const segmentClass = (active) =>
`${BTN} ${active
? 'border-hmi-accent bg-hmi-accent text-hmi-bg'
: 'border-hmi-line bg-transparent text-hmi-muted [@media(hover:hover)]:hover:text-hmi-text'}`;
const FIELD =
'block min-h-[44px] w-full border border-hmi-line bg-hmi-bg px-3 text-hmi-text ' +
'focus:border-hmi-accent focus:outline-none';
const LABEL = 'mb-1.5 block text-[11px] font-medium uppercase tracking-[0.12em] text-hmi-muted';
const SECTION_TITLE = 'text-sm font-semibold uppercase tracking-[0.14em] text-hmi-text';
const SMALL_BTN =
'min-h-[36px] border px-3 text-xs font-semibold uppercase tracking-[0.08em] transition active:translate-y-px';
const rateTone = (rate) => (rate >= 80 ? 'ok' : rate >= 50 ? 'warn' : 'err');
const RATE_BG = { ok: 'bg-hmi-ok', warn: 'bg-hmi-warn', err: 'bg-hmi-err' };
const DebugDashboard = () => {
const [latestScan, setLatestScan] = useState(null);
const [svgType, setSvgType] = useState("vertical");
const [loading, setLoading] = useState(true);
const [filesLoading, setFilesLoading] = useState(true);
const [error, setError] = useState(null);
const [warning, setWarning] = useState(null);
const [expandedIterations, setExpandedIterations] = useState({});
const [selectedFeature, setSelectedFeature] = useState("");
const [searchQuery, setSearchQuery] = useState("");
const [filterStatus, setFilterStatus] = useState("all");
const [showResults, setShowResults] = useState(false);
const [selectedFile, setSelectedFile] = useState("");
const [availableFiles, setAvailableFiles] = useState([]);
const [index, setIndex] = useState(0);
// New state for historical data functionality
const [dataMode, setDataMode] = useState("latest"); // "latest" or "historical"
const [availableDates, setAvailableDates] = useState([]);
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [datesLoading, setDatesLoading] = useState(false);
const resultsRef = useRef(null);
// On narrow screens the results panel stacks below; make it visible when opened
useEffect(() => {
if (showResults && !window.matchMedia('(min-width: 1280px)').matches) {
resultsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, [showResults]);
// Extract feature list for dropdown
const featureList = useMemo(() => {
return Array.from(new Set(
latestScan?.scan_results?.flatMap(iter =>
iter.features?.filter(f => !["Index", "OK", "Processing Time (s)"].includes(f.name))
.map(f => f.name)
) || []
));
}, [latestScan]);
const arr1 = [
"Feature6 (L248)",
"Feature8 (L79.73)",
"Feature7 (L42)",
"Feature10 (R2-35)",
"Feature12 (88.6)",
"Feature9 (R1-50)",
"Feature14 (81.5)"
];
const arr2 = [
"Feature15 (L23.4)",
"Feature17 (2C)",
"Feature4 (25mm/2)",
"Feature11 (3mm)",
"Feature16 (L17.2)",
"Feature3 (23.1)",
"Feature13 (10.6)"
];
// Initialize default dates (yesterday)
useEffect(() => {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayStr = yesterday.toISOString().split('T')[0];
setStartDate(yesterdayStr);
setEndDate(yesterdayStr);
}, []);