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 (
); } if (error) { return (
{error}
); } if (warning && (!latestScan || !latestScan.scan_results || latestScan.scan_results.length === 0)) { return (
{warning}
Select a different date range or switch to the latest data.
); } 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 (
{/* SVG Type Buttons */}
{svgTypes.map((type) => ( ))}
{/* Iteration Selector */}
{iterationIndices.map((idx) => ( ))}
{/* SVG Container with Arrow Navigation */}
{featureLabels.map(({ idx, x, y }, i) => { const { name, value } = getFeature(idx, `feature${idx + 1}`); const border = labelBorders[idx % labelBorders.length]; return (
{name}
{value}
); })}
{/* Right Arrow Navigation Button */}
); }; const renderEnhancedSummary = () => { const tone = rateTone(stats.passRate); return (
Scan summary {dataMode === "historical" && startDate && endDate ? `${startDate} – ${endDate}` : new Date().toLocaleString('en-US') }
{warning && (
{warning}
)}
0 ? 'err' : 'neutral'} />
Pass rate {stats.passRate.toFixed(1)}%
{stats.failed > 0 && Object.keys(stats.failureReasons).length > 0 && (
Technical drawing
Most common failure reasons
{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 ( ); }) }
Feature Count Distribution
{count}
{percentage}%
)}
); }; const renderControlPanel = () => { return (
{/* Data Mode Toggle */}
Data mode
{/* Latest Data Controls */} {dataMode === "latest" && (
{filesLoading ? (
Loading files
) : (
)}
)} {/* Historical Data Controls */} {dataMode === "historical" && (
setStartDate(e.target.value)} />
setEndDate(e.target.value)} />
{availableDates.length > 0 && (
Recorded dates ({availableDates.length})
{availableDates.slice(0, 10).join(', ')} {availableDates.length > 10 && ` … and ${availableDates.length - 10} more`}
)}
)}
setSearchQuery(e.target.value)} />
); }; 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 (
toggleIteration(index)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleIteration(index); } }} >
{indexFeature && ( Index {indexFeature.value} )}
{passedFeatures}/{totalFeatures} features passed
{processingTimeFeature && ( {processingTimeFeature.value.toFixed(1)} s )} {hasFailed ? "✕ Failed" : "✓ Passed"}
{isExpanded && (
{hasFailed && iterationData.status.failure_reasons?.length > 0 && (
Failure reasons
    {iterationData.status.failure_reasons.map((reason, idx) => (
  • {reason}
  • ))}
)}
{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 ( ); })}
Feature Value Tolerance check
{hasFailed && ( ✕ )} {hasPassed && ( ✓ )} {feature.name}
{typeof feature.value === "object" && feature.value !== null ? JSON.stringify(feature.value) : typeof feature.value === "number" ? feature.value.toFixed(3) : feature.value} {!tc ? ( Tolerance not defined ) : tc.error ? ( {tc.error} ) : (
Target{" "} {tc.target}
Tolerance{" "} ±{tc.tolerance}
Deviation{" "} {distance.toFixed(3)}
Remaining{" "} {tc.tolerance_remaining?.toFixed(3) || "N/A"}
{tolerance > 0 && (
{utilization.toFixed(1)}%
{(tc.target - tc.tolerance).toFixed(1)} {tc.target} {(tc.target + tc.tolerance).toFixed(1)}
)}
)}
{processingTimeFeature && (
Processing time{" "} {processingTimeFeature.value.toFixed(2)} s
)}
Feature pass rate{" "} {passedFeatures}/{totalFeatures} ({passRate.toFixed(1)}%)
)}
); }; const resultCount = filteredIterations?.length || 0; return (
{/* Side-by-side layout only on wide screens; columns got cramped on 1024px touch screens */}
Scan results
{/* Results panel tab: fixed on the right edge, wide for touch */} {renderEnhancedSummary()} {renderControlPanel()}
{selectedFeature && ( )}
{showResults && (
{resultCount} / {latestScan?.scan_results?.length ?? 0} iterations shown
{filteredIterations.length > 0 ? ( filteredIterations.slice().reverse().map((iteration, idx) => (
{renderIteration(iteration, idx)}
)) ) : (
No results match the filters
Try changing your search criteria
)}
)}
); }; export default DebugDashboard;