fix: Mock-Datenzugriff über API-Handler in Entwicklungsumgebung integriert

- fetchAnalogInputsHistoryService angepasst: nutzt /api/cpl/fetchAnalogInputsHistory bei NODE_ENV=development
- Produktionsdaten weiterhin direkt vom CPL-Webserver über CGI-Endpunkte geladen
- Chart- und Redux-Datenstrom jetzt vollständig stabil in Entwicklung und Produktion
- Fehler beim direkten Zugriff auf Mock-Dateien in Pages Router Next.js behoben
This commit is contained in:
ISA
2025-04-29 10:55:20 +02:00
parent 40e2b54836
commit e341f43204
6 changed files with 174 additions and 109 deletions

View File

@@ -1,109 +1,121 @@
"use client"; "use client"; // components/main/analogeEingaenge/AnalogInputsChart.tsx
// components/main/analogeEingaenge/AnalogInputsChart.tsx import React, { useEffect } from "react";
import React, { useState, useEffect } from "react"; import { Line } from "react-chartjs-2";
import { import {
LineChart, Chart as ChartJS,
Line, LineElement,
XAxis, PointElement,
YAxis, CategoryScale,
CartesianGrid, LinearScale,
Tooltip, Tooltip,
ResponsiveContainer, Legend,
} from "recharts"; Filler,
TimeScale,
} from "chart.js";
import "chartjs-adapter-date-fns";
import { useSelector, useDispatch } from "react-redux";
import type { RootState, AppDispatch } from "../../../redux/store";
import { fetchAnalogInputsHistoryThunk } from "../../../redux/thunks/fetchAnalogInputsHistoryThunk";
interface HistoryDataPoint { ChartJS.register(
t: string; // Timestamp LineElement,
m: number; // Messwert (Value) PointElement,
v: number; // Gültigkeit (0/1) CategoryScale,
} LinearScale,
Tooltip,
Legend,
Filler,
TimeScale
);
const colors = [
"#007bff",
"#28a745",
"#dc3545",
"#ffc107",
"#17a2b8",
"#6f42c1",
"#fd7e14",
"#20c997",
];
export default function AnalogInputsChart() { export default function AnalogInputsChart() {
const [selectedInput, setSelectedInput] = useState<number>(1); const dispatch = useDispatch<AppDispatch>();
const [historyData, setHistoryData] = useState<HistoryDataPoint[]>([]); const { data, isLoading, error } = useSelector(
const [isLoading, setIsLoading] = useState(false); (state: RootState) => state.analogInputsHistory
);
// Simulierter API-Aufruf für Historische Daten
const fetchHistoryData = async (inputNumber: number) => {
setIsLoading(true);
try {
// Hier ersetzt du später mit deinem echten API-Call
// Beispiel: const response = await fetch(`/api/analogInputs/history?input=${inputNumber}`);
// const data = await response.json();
// Temporär: Dummy-Daten für Simulation
const now = new Date();
const dummyData = Array.from({ length: 24 }, (_, i) => ({
t: new Date(now.getTime() - i * 60 * 60 * 1000).toISOString(), // letzte 24 Stunden
m: Math.random() * 100, // Zufälliger Wert
v: 1, // Gültig
})).reverse();
setHistoryData(dummyData);
} catch (error) {
console.error("Fehler beim Laden der Historie:", error);
setHistoryData([]);
} finally {
setIsLoading(false);
}
};
useEffect(() => { useEffect(() => {
fetchHistoryData(selectedInput); dispatch(fetchAnalogInputsHistoryThunk());
}, [selectedInput]); }, [dispatch]);
const handleInputChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const datasets = Object.entries(data).map(([key, inputData], index) => ({
setSelectedInput(Number(e.target.value)); label: `Eingang ${Number(key) - 99}`,
data: inputData.map((point: any) => ({
x: point.t,
y: point.m,
})),
fill: false,
borderColor: colors[index % colors.length],
backgroundColor: colors[index % colors.length],
tension: 0.3,
}));
const chartData = {
datasets,
};
const chartOptions = {
responsive: true,
plugins: {
legend: {
position: "top" as const,
labels: {
usePointStyle: true,
},
},
tooltip: {
mode: "index" as const,
intersect: false,
},
},
scales: {
x: {
type: "time" as const,
time: {
unit: "hour",
tooltipFormat: "HH:mm",
displayFormats: {
hour: "HH:mm",
},
},
title: {
display: true,
text: "Zeit",
},
},
y: {
title: {
display: true,
text: "Messwert",
},
},
},
}; };
return ( return (
<div className="w-full bg-white shadow-md rounded-lg p-4 border border-gray-200"> <div className="w-full bg-white shadow-md rounded-lg p-4 border border-gray-200">
<h2 className="text-lg font-bold mb-4"> <h2 className="text-lg font-bold mb-4">
Historische Werte für Analogen Eingang der letzten 24 Stunden Alle analogen Eingänge Verlauf der letzten 24 Stunden
</h2> </h2>
<div className="mb-4">
<label className="mr-2 font-semibold" htmlFor="inputSelect">
Eingang wählen:
</label>
<select
id="inputSelect"
className="border rounded p-1"
value={selectedInput}
onChange={handleInputChange}
>
{[...Array(8)].map((_, index) => (
<option key={index} value={index + 1}>
Eingang {index + 1}
</option>
))}
</select>
</div>
{isLoading ? ( {isLoading ? (
<div className="text-center text-gray-500">Lade Daten...</div> <div className="text-center text-gray-500">Lade Daten...</div>
) : error ? (
<div className="text-center text-red-500">Fehler: {error}</div>
) : ( ) : (
<div className="w-full h-[350px]"> <div className="w-full h-[400px]">
<ResponsiveContainer width="100%" height="100%"> <Line data={chartData} options={chartOptions} />
<LineChart
data={historyData}
margin={{ top: 10, right: 20, left: 0, bottom: 10 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="t"
tickFormatter={(str) => str.substring(11, 16)}
/>
<YAxis />
<Tooltip labelFormatter={(label) => `Zeit: ${label}`} />
<Line
type="monotone"
dataKey="m"
stroke="#4A90E2"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
</div> </div>
)} )}
</div> </div>

View File

@@ -6,5 +6,5 @@
2: Patch oder Hotfix (Bugfixes oder kleine Änderungen). 2: Patch oder Hotfix (Bugfixes oder kleine Änderungen).
*/ */
const webVersion = "1.6.305"; const webVersion = "1.6.306";
export default webVersion; export default webVersion;

View File

@@ -0,0 +1,41 @@
// /redux/slices/analogInputsHistorySlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { fetchAnalogInputsHistoryThunk } from "../thunks/fetchAnalogInputsHistoryThunk";
type InputHistoryState = {
data: Record<number, any[]>;
isLoading: boolean;
error: string | null;
};
const initialState: InputHistoryState = {
data: {},
isLoading: false,
error: null,
};
const analogInputsHistorySlice = createSlice({
name: "analogInputsHistory",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchAnalogInputsHistoryThunk.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(
fetchAnalogInputsHistoryThunk.fulfilled,
(state, action: PayloadAction<Record<number, any[]>>) => {
state.data = action.payload;
state.isLoading = false;
}
)
.addCase(fetchAnalogInputsHistoryThunk.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload as string;
});
},
});
export default analogInputsHistorySlice.reducer;

View File

@@ -23,6 +23,7 @@ import tdmSingleChartReducer from "./slices/tdmSingleChartSlice";
import tdrReferenceChartDataBySlotReducer from "./slices/tdrReferenceChartDataBySlotSlice"; import tdrReferenceChartDataBySlotReducer from "./slices/tdrReferenceChartDataBySlotSlice";
import loopChartTypeSlice from "./slices/loopChartTypeSlice"; import loopChartTypeSlice from "./slices/loopChartTypeSlice";
import systemVoltTempReducer from "./slices/systemVoltTempSlice"; import systemVoltTempReducer from "./slices/systemVoltTempSlice";
import analogInputsHistoryReducer from "./slices/analogInputsHistorySlice";
const store = configureStore({ const store = configureStore({
reducer: { reducer: {
@@ -48,6 +49,7 @@ const store = configureStore({
tdrReferenceChartDataBySlotSlice: tdrReferenceChartDataBySlotReducer, tdrReferenceChartDataBySlotSlice: tdrReferenceChartDataBySlotReducer,
loopChartType: loopChartTypeSlice, loopChartType: loopChartTypeSlice,
systemVoltTemp: systemVoltTempReducer, systemVoltTemp: systemVoltTempReducer,
analogInputsHistory: analogInputsHistoryReducer,
}, },
}); });

View File

@@ -0,0 +1,15 @@
// /redux/thunks/fetchAnalogInputsHistoryThunk.ts
import { createAsyncThunk } from "@reduxjs/toolkit";
import { fetchAnalogInputsHistoryService } from "../../services/fetchAnalogInputsHistoryService";
export const fetchAnalogInputsHistoryThunk = createAsyncThunk(
"analogInputsHistory/fetch",
async (_, { rejectWithValue }) => {
try {
const data = await fetchAnalogInputsHistoryService();
return data;
} catch (error: any) {
return rejectWithValue(error.message || "Unbekannter Fehler");
}
}
);

View File

@@ -20,29 +20,24 @@ export async function fetchAnalogInputsHistoryService(): Promise<
const isDev = process.env.NODE_ENV === "development"; const isDev = process.env.NODE_ENV === "development";
if (isDev) {
// ⬇️ ENTWICKLUNG: über API-Handler
const response = await fetch("/api/cpl/fetchAnalogInputsHistory");
if (!response.ok) throw new Error("Fehler beim Laden der Mock-Daten");
return await response.json();
}
// ⬇️ PRODUKTION: direkt vom CPL-Webserver holen
for (let i = 0; i < 8; i++) { for (let i = 0; i < 8; i++) {
const inputNumber = i + 1; // 18 const inputNumber = i + 1;
const sourceId = 99 + inputNumber; // 100107 für AE1AE8 const sourceId = 99 + inputNumber;
try { try {
let data: any[]; const url = `${window.location.origin}/CPL?Service/empty.acp&DIA0=${fromDate};${toDate};${sourceId};1`;
const response = await fetch(url);
if (isDev) { if (!response.ok)
// ⬇️ Lädt lokale Mock-Dateien (z.B. /api/cpl/fetchAnalogInputsHistory) throw new Error(`Fehler bei AE${inputNumber}: ${response.status}`);
const response = await fetch( const data = await response.json();
`/apiMockData/analogInputsHistoryData/analogInput${inputNumber}.json`
);
if (!response.ok) throw new Error("Mock-Daten nicht verfügbar");
data = await response.json();
} else {
// ⬇️ Holt Live-Daten über CPL-HTTP-Endpunkt
const url = `${window.location.origin}/CPL?Service/empty.acp&DIA0=${fromDate};${toDate};${sourceId};1`;
const response = await fetch(url);
if (!response.ok)
throw new Error(`Fehler bei AE${inputNumber}: ${response.status}`);
data = await response.json();
}
result[sourceId] = data; result[sourceId] = data;
} catch (error) { } catch (error) {
console.error(`❌ Fehler beim Laden von AE${inputNumber}:`, error); console.error(`❌ Fehler beim Laden von AE${inputNumber}:`, error);