import React, { useEffect, useState } from 'react'; interface KPI_TableProps { siteId: string; month: string; // format: "YYYY-MM" } interface MonthlyKPI { site: string; month: string; yield_kwh: number | null; consumption_kwh: number | null; grid_draw_kwh: number | null; efficiency: number | null; peak_demand_kw: number | null; // ✅ new avg_power_factor: number | null; // ✅ new load_factor: number | null; } const KPI_Table: React.FC = ({ siteId, month }) => { const [kpiData, setKpiData] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchKPI = async () => { setLoading(true); try { const res = await fetch(`http://localhost:8000/kpi/monthly?site=${siteId}&month=${month}`); const data = await res.json(); setKpiData(data); } catch (err) { console.error('Failed to fetch KPI:', err); setKpiData(null); // fallback } finally { setLoading(false); } }; if (siteId && month) fetchKPI(); }, [siteId, month]); if (!siteId) { return (

Monthly KPI

No site selected

); } if (loading) { return (

Monthly KPI

Loading...

); } // Use optional chaining and nullish coalescing to safely default values to 0 const yield_kwh = kpiData?.yield_kwh ?? 0; const consumption_kwh = kpiData?.consumption_kwh ?? 0; const grid_draw_kwh = kpiData?.grid_draw_kwh ?? 0; const efficiency = kpiData?.efficiency ?? 0; const peak_demand_kw = kpiData?.peak_demand_kw ?? 0; const power_factor = kpiData?.avg_power_factor ?? 0; const load_factor = kpiData?.load_factor ?? 0; const data = [ { kpi: 'Monthly Yield', value: `${yield_kwh.toFixed(0)} kWh` }, { kpi: 'Monthly Consumption', value: `${consumption_kwh.toFixed(0)} kWh` }, { kpi: 'Monthly Grid Draw', value: `${grid_draw_kwh.toFixed(0)} kWh` }, { kpi: 'Efficiency', value: `${efficiency.toFixed(1)}%` }, { kpi: 'Peak Demand', value: `${peak_demand_kw.toFixed(2)} kW` }, // ✅ added { kpi: 'Power Factor', value: `${power_factor.toFixed(2)} kW` }, // ✅ added { kpi: 'Load Factor', value: `${load_factor.toFixed(2)} kW` }, // ✅ added ]; return (

Monthly KPI

{data.map((row) => ( ))}
KPI Value
{row.kpi} {row.value}
); }; export default KPI_Table;