feat: AnalogInputsChart mit DateRangePicker und vollständiger Redux-Integration erweitert

- analogInputsHistorySlice angepasst: zeitraum, vonDatum, bisDatum und data hinzugefügt
- Typdefinitionen im Slice und Thunk korrigiert
- getAnalogInputsHistoryThunk erweitert, um vonDatum und bisDatum zu akzeptieren
- DateRangePicker korrekt in AnalogInputsChart.tsx integriert
- Fehler bei Selector-Zugriffen und Dispatch behoben
This commit is contained in:
ISA
2025-07-11 14:01:57 +02:00
parent d278a79030
commit 99294f26da
11 changed files with 187 additions and 223 deletions

View File

@@ -1,12 +1,8 @@
"use client";
type AnalogInput = {
id: number;
label: string;
unit: string;
};
import React, { useEffect } from "react";
import React, { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "@/redux/store";
import { Line } from "react-chartjs-2";
import { getColor } from "@/utils/colors";
import {
Chart as ChartJS,
LineElement,
@@ -18,19 +14,19 @@ import {
Filler,
TimeScale,
} from "chart.js";
import type { ChartOptions } from "chart.js";
import "chartjs-adapter-date-fns";
import { de } from "date-fns/locale";
import { useSelector, useDispatch } from "react-redux";
import type { RootState, AppDispatch } from "@/redux/store";
import { getAnalogInputsHistoryThunk } from "@/redux/thunks/getAnalogInputsHistoryThunk";
import DateRangePicker from "@/components/common/DateRangePicker";
import { Listbox } from "@headlessui/react";
import {
setVonDatum,
setBisDatum,
} from "@/redux/slices/analogInputsChartSlice";
setZeitraum,
} from "@/redux/slices/analogInputsHistorySlice";
import DateRangePicker from "@/components/common/DateRangePicker";
import { Listbox } from "@headlessui/react";
import { getColor } from "@/utils/colors";
// Basis-Registrierung (ohne Zoom-Plugin)
ChartJS.register(
LineElement,
PointElement,
@@ -42,160 +38,142 @@ ChartJS.register(
TimeScale
);
type AnalogInputHistoryPoint = {
t: string;
m: number;
};
export default function AnalogInputsChart({
selectedId,
}: {
selectedId: number | null;
}) {
const selectedInput = useSelector(
(state: RootState) => state.selectedAnalogInput
) as unknown as AnalogInput | null;
const dispatch = useDispatch<AppDispatch>();
const chartRef = useRef<any>(null);
type AnalogInputHistoryPoint = { t: string | number | Date; m: number };
const { data } = useSelector(
const { zeitraum, vonDatum, bisDatum, data, isLoading } = useSelector(
(state: RootState) => state.analogInputsHistory
) as {
data: { [key: string]: AnalogInputHistoryPoint[] };
};
const zeitraum = useSelector(
(state: RootState) => state.analogInputsHistory.zeitraum
);
const handleFetchData = () => {
if (!selectedId || !zeitraum) return;
dispatch(getAnalogInputsHistoryThunk({ eingang: selectedId, zeitraum }));
useEffect(() => {
const today = new Date();
const vor30Tagen = new Date(today);
vor30Tagen.setDate(today.getDate() - 30);
if (!vonDatum) dispatch(setVonDatum(vor30Tagen.toISOString().slice(0, 10)));
if (!bisDatum) dispatch(setBisDatum(today.toISOString().slice(0, 10)));
}, [dispatch, vonDatum, bisDatum]);
const handleFetchChartData = () => {
if (!selectedId) return;
dispatch(
getAnalogInputsHistoryThunk({
eingang: selectedId,
zeitraum,
vonDatum,
bisDatum,
})
);
};
useEffect(() => {
if (selectedId && zeitraum) {
dispatch(getAnalogInputsHistoryThunk({ eingang: selectedId, zeitraum }));
}
}, [dispatch, selectedId, zeitraum]);
// ✅ Zoom-Plugin dynamisch importieren und registrieren
useEffect(() => {
const loadZoomPlugin = async () => {
if (typeof window !== "undefined") {
const zoomPlugin = (await import("chartjs-plugin-zoom")).default;
if (!ChartJS.registry.plugins.get("zoom")) {
ChartJS.register(zoomPlugin);
}
}
};
loadZoomPlugin();
}, []);
if (!selectedId) {
return (
<div className="text-gray-500">Bitte einen Messwerteingang auswählen</div>
);
}
const key = String(selectedId + 99);
const inputData = data[key];
if (!inputData) {
return (
<div className="text-red-500">
Keine Verlaufsdaten für Messwerteingang {selectedId} gefunden.
</div>
);
}
const dataKey = selectedId ? String(selectedId + 99) : null;
const chartData = {
datasets: [
{
label: `Messkurve ${selectedInput?.label ?? "Eingang"} [${
selectedInput?.unit ?? ""
}]`,
data: inputData.map((point: AnalogInputHistoryPoint) => ({
x: point.t,
y: point.m,
})),
fill: false,
borderColor: getColor("littwin-blue"),
backgroundColor: "rgba(59,130,246,0.5)",
borderWidth: 2,
pointRadius: 0,
pointHoverRadius: 10,
tension: 0.1,
},
],
datasets:
dataKey && data[dataKey]
? [
{
label: `Messwerteingang ${selectedId}`,
data: data[dataKey].map((p: AnalogInputHistoryPoint) => ({
x: new Date(p.t),
y: p.m,
})),
fill: false,
borderColor: getColor("littwin-blue"),
backgroundColor: "rgba(59,130,246,0.3)",
borderWidth: 2,
pointRadius: 0,
tension: 0.1,
},
]
: [],
};
const chartOptions = {
const chartOptions: ChartOptions<"line"> = {
responsive: true,
plugins: {
legend: { position: "top" as const },
legend: { position: "top" },
title: { display: true, text: "Verlauf" },
tooltip: {
mode: "index" as const,
mode: "index",
intersect: false,
callbacks: {
label: function (context: import("chart.js").TooltipItem<"line">) {
const y = context.parsed.y;
return `Messwert: ${y}`;
},
title: function (
tooltipItems: import("chart.js").TooltipItem<"line">[]
) {
const date = tooltipItems[0].parsed.x;
return `Zeitpunkt: ${new Date(date).toLocaleString("de-DE")}`;
},
},
},
title: {
display: true,
text: `Verlauf der letzten 30 Tage`,
},
zoom: {
pan: {
enabled: true,
mode: "x" as const,
},
zoom: {
wheel: { enabled: true },
pinch: { enabled: true },
mode: "x" as const,
label: (ctx) => `Messwert: ${ctx.parsed.y}`,
title: (items) =>
`Zeitpunkt: ${new Date(items[0].parsed.x).toLocaleString("de-DE")}`,
},
},
},
scales: {
x: {
type: "time" as const,
type: "time",
time: {
unit: "day" as const, // nur Datum in Achse
tooltipFormat: "dd.MM.yyyy HH:mm", // aber Uhrzeit im Tooltip sichtbar
displayFormats: {
day: "dd.MM.yyyy",
},
},
adapters: {
date: {
locale: de,
},
},
title: {
display: true,
text: "Zeit",
},
},
y: {
title: {
display: true,
text: `Messwert [${selectedInput?.unit ?? ""}]`,
unit: "day",
tooltipFormat: "dd.MM.yyyy HH:mm",
displayFormats: { day: "dd.MM.yyyy" },
},
adapters: { date: { locale: de } },
title: { display: true, text: "Zeit" },
},
y: { title: { display: true, text: "Messwert" } },
},
};
return (
<div className="w-full h-full">
<Line data={chartData} options={chartOptions} />
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-4 mb-2">
<DateRangePicker />
<Listbox value={zeitraum} onChange={(v) => dispatch(setZeitraum(v))}>
<div className="relative w-48">
<Listbox.Button className="w-full border px-3 py-1 rounded bg-white flex justify-between items-center text-sm">
<span>
{zeitraum === "DIA0"
? "Alle Messwerte"
: zeitraum === "DIA1"
? "Stündlich"
: "Täglich"}
</span>
<i className="bi bi-chevron-down text-gray-400" />
</Listbox.Button>
<Listbox.Options className="absolute z-10 mt-1 w-full border bg-white shadow rounded text-sm">
{["DIA0", "DIA1", "DIA2"].map((option) => (
<Listbox.Option
key={option}
value={option}
className="px-4 py-1 cursor-pointer hover:bg-gray-200"
>
{option === "DIA0"
? "Alle Messwerte"
: option === "DIA1"
? "Stündlich"
: "Täglich"}
</Listbox.Option>
))}
</Listbox.Options>
</div>
</Listbox>
<button
onClick={handleFetchChartData}
className="px-4 py-1 bg-littwin-blue text-white rounded text-sm"
>
Daten laden
</button>
</div>
<div className="h-[50vh] w-full">
<Line ref={chartRef} data={chartData} options={chartOptions} />
</div>
</div>
);
}