This commit is contained in:
Ismail Ali
2025-06-26 22:56:20 +02:00
parent 137839da98
commit b9651a53a9
82 changed files with 7476 additions and 4171 deletions

View File

@@ -6,6 +6,6 @@ NEXT_PUBLIC_USE_MOCK_BACKEND_LOOP_START=false
NEXT_PUBLIC_EXPORT_STATIC=false
NEXT_PUBLIC_USE_CGI=false
# App-Versionsnummer
NEXT_PUBLIC_APP_VERSION=1.6.482
NEXT_PUBLIC_APP_VERSION=1.6.483
NEXT_PUBLIC_CPL_MODE=json # json (Entwicklungsumgebung) oder jsSimulatedProd (CPL ->CGI-Interface-Simulator) oder production (CPL-> CGI-Interface Platzhalter)

View File

@@ -5,5 +5,5 @@ NEXT_PUBLIC_CPL_API_PATH=/CPL
NEXT_PUBLIC_EXPORT_STATIC=true
NEXT_PUBLIC_USE_CGI=true
# App-Versionsnummer
NEXT_PUBLIC_APP_VERSION=1.6.482
NEXT_PUBLIC_APP_VERSION=1.6.483
NEXT_PUBLIC_CPL_MODE=production

View File

@@ -1,6 +1,20 @@
{
"extends": [
"next",
"next/core-web-vitals",
"next/typescript"
]
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": ["@typescript-eslint", "react"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
// deine Regeln hier
}
}

View File

@@ -1,7 +1,7 @@
#!/bin/sh
echo "🔄 Version wird automatisch erhöht (bumpVersion.ts)..."
npx husky add .husky/pre-commit "npm run check"
npm run check
# 1. Version erhöhen
npx ts-node scripts/bumpVersion.ts || exit 1
@@ -14,3 +14,4 @@ node ./scripts/updateChangelogFromCommit.js "$COMMIT_MSG" || exit 1
# 4. Dateien zum Commit hinzufügen
git add package.json package-lock.json CHANGELOG.md .env.development .env.production
npm run check

View File

@@ -1,3 +1,8 @@
## [1.6.483] 2025-06-26
- EsLint
---
## [1.6.482] 2025-06-26
- feat: Tabellenkopf in Berichte-Seite fixiert und Scrollen verbessert

View File

@@ -1,129 +0,0 @@
import React from "react";
import { render, fireEvent, screen } from "@testing-library/react";
import configureStore from "redux-mock-store";
import { Provider } from "react-redux";
import "@testing-library/jest-dom";
import Kue705FO from "../../../components/main/kabelueberwachung/kue705FO/Kue705FO";
// Mocks für externe Abhängigkeiten
jest.mock("chart.js/auto", () => ({
default: {
register: jest.fn(),
},
Chart: jest.fn().mockImplementation(() => ({
destroy: jest.fn(),
update: jest.fn(),
})),
}));
jest.mock("chartjs-plugin-zoom", () => ({}));
// Initialzustand für Redux
const mockStore = configureStore([]);
const initialState = {
variables: {
kuePSTmMinus96V: [0],
kueCableBreak: [0],
kueGroundFault: [0],
kueAlarm1: [0],
kueAlarm2: [0],
kueOverflow: [0],
kueVersion: [419],
tdrActive: [1],
},
auth: {
isAdminLoggedIn: true, // Füge dies hinzu
},
};
// Standard-Props
const defaultProps = {
isolationswert: 200,
schleifenwiderstand: 5.6,
modulName: "TestModul",
kueOnline: 1,
slotIndex: 0,
tdrLocation: [2.5],
};
describe("Kue705FO Integration Tests", () => {
let store: ReturnType<typeof mockStore>;
beforeEach(() => {
store = mockStore(initialState);
});
it("should render correctly with default props", () => {
render(
<Provider store={store}>
<Kue705FO {...defaultProps} />
</Provider>
);
// Überprüfen, ob die Basis-Darstellung korrekt ist
expect(screen.getByText("KÜ705-FO")).toBeInTheDocument();
expect(screen.getByText("TestModul")).toBeInTheDocument();
});
it("should toggle between TDR and Schleife modes", () => {
render(
<Provider store={store}>
<Kue705FO {...defaultProps} />
</Provider>
);
// Überprüfen, ob Schleife aktiv ist
expect(screen.getByText("Schleifenwiderstand [kOhm]")).toBeInTheDocument();
expect(screen.getByText("5.6 KOhm")).toBeInTheDocument();
// TDR-Button klicken
fireEvent.click(screen.getByText("TDR"));
// Überprüfen, ob TDR aktiv ist
expect(screen.getByText("Entfernung [Km]")).toBeInTheDocument();
expect(screen.getByText("2.5 Km")).toBeInTheDocument();
// Zurück zu Schleife wechseln
fireEvent.click(screen.getByText("Schleife"));
expect(screen.getByText("Schleifenwiderstand [kOhm]")).toBeInTheDocument();
});
it("should open and close the settings modal", () => {
render(
<Provider store={store}>
<Kue705FO {...defaultProps} />
</Provider>
);
// Modal öffnen
fireEvent.click(screen.getByText("⚙"));
expect(screen.getByText("KUE Einstellung - Slot 1")).toBeInTheDocument();
// Modal schließen
fireEvent.click(screen.getByRole("button", { name: /x/i }));
expect(
screen.queryByText("KUE Einstellung - Slot 1")
).not.toBeInTheDocument();
});
it("should disable TDR button when tdrActive is 0", () => {
// Zustand aktualisieren
store = mockStore({
...initialState,
variables: {
...initialState.variables,
tdrActive: [0],
},
});
render(
<Provider store={store}>
<Kue705FO {...defaultProps} />
</Provider>
);
// TDR-Button sollte deaktiviert sein
const tdrButton = screen.getByText("TDR");
expect(tdrButton).toBeDisabled();
});
});

View File

@@ -1,7 +0,0 @@
// __tests__/example.test.ts
describe('Basic Test', () => {
it('should pass', () => {
expect(true).toBe(true);
});
});

View File

@@ -7,7 +7,7 @@ import SettingsModal from "@/components/header/settingsModal/SettingsModal";
import { RootState } from "@/redux/store";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";
import decodeToken from "@/utils/decodeToken";
import { getSystemSettingsThunk } from "@/redux/thunks/getSystemSettingsThunk";
function Header() {
@@ -16,7 +16,6 @@ function Header() {
const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false);
// Removed duplicate declaration of deviceName
const handleSettingsClick = () => setShowSettingsModal(true);
const handleCloseSettingsModal = () => setShowSettingsModal(false);
const handleLogout = () => {
@@ -26,13 +25,6 @@ function Header() {
router.push("/offline.html"); // Weiterleitung
};
const handleLogin = () => {
const token = JSON.stringify({ exp: Date.now() + 5 * 60 * 1000 }); // Beispiel-Token mit 5 Minuten Ablaufzeit
sessionStorage.setItem("token", token); // Token speichern
localStorage.setItem("isAdminLoggedIn", "true"); // Admin-Status setzen
setIsAdminLoggedIn(true); // Zustand sofort aktualisieren
};
useEffect(() => {
// Initialer Check beim Laden der Komponente
const isAdmin = localStorage.getItem("isAdminLoggedIn") === "true";

View File

@@ -1,5 +1,5 @@
"use client"; // components/header/settingsModal/SettingsModal.tsx
import React, { useState, useEffect } from "react";
import React, { useState } from "react";
import ReactModal from "react-modal";
import "bootstrap-icons/font/bootstrap-icons.css";
import { RootState } from "../../../redux/store";
@@ -8,13 +8,7 @@ import handleClearDatabase from "./handlers/handleClearDatabase";
import handleReboot from "./handlers/handleReboot";
import handleSetDateTime from "./handlers/handleSetDateTime";
import handleSubmit from "./handlers/handleSubmit";
import bcrypt from "bcryptjs";
import CryptoJS from "crypto-js";
import { useAdminAuth } from "./hooks/useAdminAuth";
import { useSystemSettings } from "./hooks/useSystemSettings";
import { generateKeyAndIV, generateToken } from "./utils/cryptoUtils";
import USERS from "./config/users";
import handleAdminLogin from "./handlers/handleAdminLogin";
ReactModal.setAppElement("#__next");
@@ -27,13 +21,6 @@ function SettingModal({
}) {
const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(showModal);
const { formValues, setFormValues } = useSystemSettings(showModal);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [showLoginForm, setShowLoginForm] = useState(false);
const deviceName_Redux = useSelector(
(state: RootState) => state.systemSettingsSlice.deviceName
);
@@ -69,11 +56,11 @@ function SettingModal({
);
const [name, setName] = useState(deviceName_Redux || "");
const [mac1, setMac1] = useState(mac1_Redux || "");
const [mac1] = useState(mac1_Redux || "");
const [ip, setIp] = useState(ip_Redux || "");
const [subnet, setSubnet] = useState(subnet_Redux || "");
const [gateway, setGateway] = useState(gateway_Redux || "");
const [systemUhr, setSystemUhr] = useState(datetime_Redux || "");
const [systemUhr] = useState(datetime_Redux || "");
const [ntp1, setNtp1] = useState(ntp1_Redux || "");
const [ntp2, setNtp2] = useState(ntp2_Redux || "");
const [ntp3, setNtp3] = useState(ntp3_Redux || "");
@@ -82,7 +69,7 @@ function SettingModal({
typeof active_Redux === "boolean" ? active_Redux : active_Redux === "true"
);
const [originalValues, setOriginalValues] = useState({
const [originalValues] = useState({
name: name,
ip: ip,
subnet: subnet,
@@ -93,6 +80,8 @@ function SettingModal({
ntpTimezone: ntpTimezone,
active: active,
});
// const [showLoginForm, setShowLoginForm] = useState(false);
const currentValues = {
name,
ip,
@@ -266,9 +255,7 @@ function SettingModal({
Neustart CPL
</button>
<button
onClick={() =>
isAdminLoggedIn ? logoutAdmin() : setShowLoginForm(true)
}
onClick={() => (isAdminLoggedIn ? logoutAdmin() : null)}
className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full md:w-auto"
>
{isAdminLoggedIn ? "Admin abmelden" : "Admin anmelden"}

View File

@@ -1,17 +1,20 @@
import React from "react";
// /components/icons/CogIcon.tsx
import Image from "next/image";
type Props = {
className?: string;
onClick?: () => void;
};
export default function CogIcon({ className, onClick }: Props) {
return (
<img
const CogIcon: React.FC<Props> = ({ className, onClick }) => (
<Image
src="/icons/mdi--cog-outline.svg"
alt="Einstellungen"
className={className}
onClick={onClick}
width={24}
height={24}
/>
);
}
export default CogIcon;

View File

@@ -46,10 +46,12 @@ export default function AnalogInputsChart({
) as unknown as AnalogInput | null;
const dispatch = useDispatch<AppDispatch>();
type AnalogInputHistoryPoint = { t: string | number | Date; m: number };
const { data } = useSelector(
(state: RootState) => state.analogInputsHistory
) as {
data: { [key: string]: any[] };
data: { [key: string]: AnalogInputHistoryPoint[] };
};
useEffect(() => {
@@ -92,7 +94,7 @@ export default function AnalogInputsChart({
label: `Messkurve ${selectedInput?.label ?? "Eingang"} [${
selectedInput?.unit ?? ""
}]`,
data: inputData.map((point: any) => ({
data: inputData.map((point: AnalogInputHistoryPoint) => ({
x: point.t,
y: point.m,
})),

View File

@@ -1,8 +1,17 @@
"use client"; // /components/main/analogeEingaenge/AnalogInputsSettingsModal.tsx
import React, { useEffect, useState } from "react";
interface AnalogInput {
id: number;
label?: string;
offset?: number | string;
factor?: number | string;
loggerInterval: string;
unit?: string;
}
interface Props {
selectedInput: any;
selectedInput: AnalogInput;
isOpen: boolean;
onClose: () => void;
}

View File

@@ -15,7 +15,7 @@ export default function AnalogInputsTable({
setIsSettingsModalOpen,
}: {
setSelectedId: (id: number) => void;
setSelectedInput: (input: any) => void;
setSelectedInput: (input: AnalogInput) => void;
setIsSettingsModalOpen: (open: boolean) => void;
}) {
const dispatch = useDispatch<AppDispatch>();

View File

@@ -9,7 +9,12 @@ import inputIcon from "@iconify/icons-mdi/input";
import loginIcon from "@iconify/icons-mdi/login";
type Props = {
openInputModal: (input: any) => void;
openInputModal: (input: {
id: number;
eingangOffline: boolean;
status: boolean;
label: string;
}) => void;
inputRange: { start: number; end: number };
};

View File

@@ -8,9 +8,10 @@ import settingsIcon from "@iconify/icons-mdi/settings";
import outputIcon from "@iconify/icons-mdi/output";
import switchIcon from "@iconify/icons-ion/switch";
import { setDigitalOutputs } from "@/redux/slices/digitalOutputsSlice";
import type { DigitalOutput } from "@/types/digitalOutput";
interface DigitalOutputsWidgetProps {
openOutputModal: (output: any) => void;
export interface DigitalOutputsWidgetProps {
openOutputModal: (output: DigitalOutput) => void;
}
export default function DigitalOutputsWidget({

View File

@@ -2,13 +2,14 @@
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../redux/store";
import type { DigitalOutput } from "@/types/digitalOutput";
export default function DigitalOutputsModal({
selectedOutput,
closeOutputModal,
isOpen,
}: {
selectedOutput: any;
selectedOutput: DigitalOutput | null;
closeOutputModal: () => void;
isOpen: boolean;
}) {
@@ -18,7 +19,7 @@ export default function DigitalOutputsModal({
const [label, setLabel] = useState("");
const [status, setStatus] = useState(false);
const [timer, setTimer] = useState(0);
const [isSaving, setIsSaving] = useState(false);
const [errorMsg, setErrorMsg] = useState("");
@@ -27,7 +28,7 @@ export default function DigitalOutputsModal({
if (isOpen && selectedOutput) {
setLabel(selectedOutput.label || "");
setStatus(selectedOutput.status || false);
setTimer(0);
setErrorMsg("");
}
}, [isOpen, selectedOutput]);
@@ -84,6 +85,7 @@ export default function DigitalOutputsModal({
}
}
} catch (err) {
console.error("Fehler beim Speichern:", err);
setErrorMsg("❌ Fehler beim Speichern.");
} finally {
setIsSaving(false);

View File

@@ -3,13 +3,12 @@
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/redux/store";
import switchIcon from "@iconify/icons-ion/switch";
import { updateInvert, updateLabel } from "@/redux/slices/digitalInputsSlice";
type InputModalProps = {
selectedInput: {
id: number;
[key: string]: any;
[key: string]: unknown;
} | null;
closeInputModal: () => void;
isOpen: boolean;
@@ -51,8 +50,24 @@ export default function InputModal({
}
}, [reduxInput, isInitialLoad]);
useEffect(() => {
if (isOpen && selectedInput) {
setIsInitialLoad(true);
}
}, [isOpen, selectedInput]);
useEffect(() => {
if (isOpen && selectedInput) {
setIsInitialLoad(true);
}
}, [isOpen, selectedInput]);
if (!isOpen || !selectedInput || !reduxInput) return null;
const handleClose = () => {
closeInputModal();
};
const sendCgiUpdate = async (param: string) => {
const url = `/CPL?/eingaenge.html&${param}`;
//console.log("📡 CGI senden:", url);
@@ -103,7 +118,15 @@ export default function InputModal({
alert("✅ Daten erfolgreich an die CPL-Hardware gesendet!");
} else {
// ENTWICKLUNGSUMGEBUNG (lokale API)
const updates: any = { id };
type Updates = {
id: number;
label?: string;
invert?: number;
timeFilter?: number;
weighting?: number;
zaehlerAktiv?: number;
};
const updates: Updates = { id };
if (label !== reduxInput.label) {
updates.label = label;
dispatch(updateLabel({ id, label }));
@@ -148,21 +171,15 @@ export default function InputModal({
setIsInitialLoad(true);
closeInputModal();
} catch (err: any) {
} catch (err: unknown) {
if (err instanceof Error) {
alert("❌ Fehler beim Speichern: " + err.message);
} else {
alert("❌ Fehler beim Speichern: Unbekannter Fehler");
}
}
};
const handleClose = () => {
setIsInitialLoad(true);
closeInputModal();
};
useEffect(() => {
if (isOpen && selectedInput) {
setIsInitialLoad(true);
}
}, [isOpen, selectedInput]);
return (
<div className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex justify-center items-center z-50">
<div className="bg-white rounded-lg shadow-lg p-6 w-1/2 max-w-lg">

View File

@@ -1,24 +1,19 @@
"use client"; // /components/modules/kue705FO/charts/ChartSwitcher.tsx
import React, { useState, useEffect } from "react";
import React, { useEffect } from "react";
import ReactModal from "react-modal";
import LoopChartActionBar from "./LoopMeasurementChart/LoopChartActionBar";
import TDRChartActionBar from "./TDRChart/TDRChartActionBar";
import LoopMeasurementChart from "./LoopMeasurementChart/LoopMeasurementChart";
import TDRChart from "./TDRChart/TDRChart";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "../../../../../redux/store";
import { RootState } from "../../../../../redux/store";
import { AppDispatch } from "@/redux/store";
import { RootState } from "@/redux/store";
import {
setChartOpen,
setFullScreen,
} from "../../../../../redux/slices/kabelueberwachungChartSlice";
import {
setSelectedSlot,
setSelectedChartType,
} from "../../../../../redux/slices/tdrChartSlice";
import { resetBrushRange } from "../../../../../redux/slices/brushSlice";
import { fetchTDMDataBySlotThunk } from "../../../../../redux/thunks/getTDMListBySlotThunk";
} from "@/redux/slices/kabelueberwachungChartSlice";
import { resetBrushRange } from "@/redux/slices/brushSlice";
import { useLoopChartLoader } from "./LoopMeasurementChart/LoopChartActionBar";
import {
@@ -26,7 +21,7 @@ import {
setBisDatum,
setSelectedMode,
setSelectedSlotType,
} from "../../../../../redux/slices/kabelueberwachungChartSlice";
} from "@/redux/slices/kabelueberwachungChartSlice";
interface ChartSwitcherProps {
isOpen: boolean;
@@ -34,11 +29,7 @@ interface ChartSwitcherProps {
slotIndex: number;
}
const ChartSwitcher: React.FC<ChartSwitcherProps> = ({
isOpen,
onClose,
slotIndex,
}) => {
const ChartSwitcher: React.FC<ChartSwitcherProps> = ({ isOpen, onClose }) => {
const dispatch = useDispatch<AppDispatch>();
const chartTitle = useSelector(
(state: RootState) => state.loopChartType.chartTitle
@@ -82,24 +73,20 @@ const ChartSwitcher: React.FC<ChartSwitcherProps> = ({
};
// **Slot und Messkurve setzen**
const setChartType = (chartType: "TDR" | "Schleife") => {
dispatch(setSelectedSlot(slotIndex));
dispatch(setSelectedChartType(chartType));
};
//-------------------------------------
// const setChartType = (chartType: "TDR" | "Schleife") => {
// dispatch(setSelectedSlot(slotIndex));
// dispatch(setSelectedChartType(chartType));
// };
const { loadLoopChartData } = useLoopChartLoader();
useEffect(() => {
if (isOpen && activeMode === "Schleife") {
loadLoopChartData();
}
}, [isOpen, activeMode]);
//-------------------------------------
// useLoopChartLoader hook
const loadLoopChartData = useLoopChartLoader();
// Slot number from Redux
const slotNumber = useSelector(
(state: RootState) => state.kabelueberwachungChartSlice.slotNumber
);
// immmer beim öffnen das Modal die letzte 30 Tage anzeigen
// immer beim Öffnen das Modal die letzten 30 Tage anzeigen
useEffect(() => {
if (isOpen && activeMode === "Schleife" && slotNumber !== null) {
const today = new Date();
@@ -113,12 +100,11 @@ const ChartSwitcher: React.FC<ChartSwitcherProps> = ({
// Warten, bis Redux gesetzt ist → dann Daten laden
setTimeout(() => {
loadLoopChartData();
loadLoopChartData.loadLoopChartData();
}, 10); // kleiner Delay, damit Redux-State sicher aktualisiert ist
}
}, [isOpen, activeMode, slotNumber]);
}, [isOpen, activeMode, slotNumber, dispatch, loadLoopChartData]);
//-----------------------------------------
return (
<ReactModal
isOpen={isOpen}

View File

@@ -4,7 +4,14 @@ import React from "react";
interface CustomTooltipProps {
active?: boolean;
payload?: any[];
payload?: Array<{
dataKey: string;
value: number;
name?: string;
color?: string;
unit?: string;
// Add other known properties here as needed
}>;
label?: string;
unit?: string;
}

View File

@@ -2,11 +2,11 @@
import React, { useEffect } from "react";
import DatePicker from "react-datepicker";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import { RootState } from "@/redux/store";
import {
setVonDatum,
setBisDatum,
} from "../../../../../../redux/slices/kabelueberwachungChartSlice";
} from "@/redux/slices/kabelueberwachungChartSlice";
import "react-datepicker/dist/react-datepicker.css";
const DateRangePicker: React.FC = () => {
@@ -38,6 +38,7 @@ const DateRangePicker: React.FC = () => {
useEffect(() => {
if (!reduxVonDatum) dispatch(setVonDatum(formatISO(thirtyDaysAgo)));
if (!reduxBisDatum) dispatch(setBisDatum(formatISO(today)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch, reduxVonDatum, reduxBisDatum]);
return (

View File

@@ -3,24 +3,22 @@
import React from "react";
import DateRangePicker from "./DateRangePicker";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import { RootState } from "@/redux/store";
import {
setVonDatum,
setBisDatum,
setLoopMeasurementCurveChartData,
setSelectedMode,
setSelectedSlotType,
setChartOpen,
setFullScreen,
setLoading,
} from "../../../../../../redux/slices/kabelueberwachungChartSlice";
import { setBrushRange } from "../../../../../../redux/slices/brushSlice";
import { setChartTitle } from "../../../../../../redux/slices/loopChartTypeSlice";
} from "@/redux/slices/kabelueberwachungChartSlice";
import { setBrushRange } from "@/redux/slices/brushSlice";
import { setChartTitle } from "@/redux/slices/loopChartTypeSlice";
//-----------------------------------------------------------------------------------useLoopChartLoader
export const useLoopChartLoader = () => {
const dispatch = useDispatch();
const { vonDatum, bisDatum, selectedMode, selectedSlotType, slotNumber } =
useSelector((state: RootState) => state.kabelueberwachungChartSlice);
const hasShownNoDataAlert = React.useRef(false);
const formatDate = (dateString: string) => {
const [year, month, day] = dateString.split("-");
@@ -77,7 +75,10 @@ export const useLoopChartLoader = () => {
} else {
dispatch(setLoopMeasurementCurveChartData([]));
dispatch(setChartOpen(false));
alert("⚠️ Keine Daten im gewählten Zeitraum.");
if (!hasShownNoDataAlert.current) {
alert("⚠️ Keine Messdaten im gewählten Zeitraum gefunden.");
hasShownNoDataAlert.current = true; // ⬅️ Nur einmal zeigen
}
}
} catch (err) {
console.error("❌ Fehler beim Laden:", err);
@@ -99,9 +100,9 @@ const LoopChartActionBar: React.FC = () => {
bisDatum,
selectedMode,
selectedSlotType,
isChartOpen,
slotNumber,
loopMeasurementCurveChartData,
isLoading,
} = useSelector((state: RootState) => state.kabelueberwachungChartSlice);

View File

@@ -1,8 +1,8 @@
"use client";
"use client"; // /components/main/kabelueberwachung/kue705FO/Charts/LoopMeasurementChart/LoopMeasurementChart.tsx
import React, { useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import { RootState } from "@/redux/store";
import {
Chart as ChartJS,
LineElement,
@@ -32,8 +32,16 @@ ChartJS.register(
import { getColor } from "../../../../../../utils/colors";
import { PulseLoader } from "react-spinners";
const usePreviousData = (data: any[]) => {
const ref = useRef<any[]>([]);
type LoopMeasurementEntry = {
t: string;
i: number;
m: number;
g: number;
a: number;
};
const usePreviousData = (data: LoopMeasurementEntry[]) => {
const ref = useRef<LoopMeasurementEntry[]>([]);
useEffect(() => {
ref.current = data;
}, [data]);
@@ -57,7 +65,10 @@ const LoopMeasurementChart = () => {
const previousData = usePreviousData(loopMeasurementCurveChartData);
// Vergleichsfunktion
const isEqual = (a: any[], b: any[]): boolean => {
const isEqual = (
a: LoopMeasurementEntry[],
b: LoopMeasurementEntry[]
): boolean => {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (
@@ -196,6 +207,7 @@ const LoopMeasurementChart = () => {
options,
});
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [loopMeasurementCurveChartData, selectedMode, vonDatum, bisDatum]);
return (

View File

@@ -1,7 +1,6 @@
// components/main/kabelueberwachung/kue705FO/Charts/TDRChart/TDRChart.tsx
"use client";
"use client"; // /components/main/kabelueberwachung/kue705FO/Charts/TDRChart/TDRChart.tsx
import React, { useEffect, useRef, useMemo } from "react";
import React, { useEffect, useRef } from "react";
import { RootState } from "../../../../../../redux/store";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "../../../../../../redux/store";
@@ -32,10 +31,6 @@ const TDRChart: React.FC<{ isFullScreen: boolean }> = ({ isFullScreen }) => {
(state: RootState) => state.tdrDataByIdSlice.dataById
);
//--------------------------------
const tdrInitialData =
selectedId !== null && tdrDataById[selectedId]
? tdrDataById[selectedId]
: [];
//--------------------------------
// Kombinierte Logik: ID hat Vorrang, sonst Initial-Daten für Slot
@@ -206,8 +201,10 @@ const TDRChart: React.FC<{ isFullScreen: boolean }> = ({ isFullScreen }) => {
}
}
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
JSON.stringify(tdrChartData),
// eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify(tdrChartData), // eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify(referenceChartData),
selectedSlot,
selectedChartType,

View File

@@ -2,11 +2,11 @@
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { useAppDispatch } from "../../../../../../redux/store";
import { RootState } from "../../../../../../redux/store";
import { fetchTDMDataBySlotThunk } from "../../../../../../redux/thunks/getTDMListBySlotThunk";
import { getTDRChartDataByIdThunk } from "../../../../../../redux/thunks/getTDRChartDataByIdThunk";
import { getReferenceCurveBySlotThunk } from "../../../../../../redux/thunks/getReferenceCurveBySlotThunk"; // ⬅ import ergänzen
import { useAppDispatch } from "@/redux/store";
import { RootState } from "@/redux/store";
import { fetchTDMDataBySlotThunk } from "@/redux/thunks/getTDMListBySlotThunk";
import { getTDRChartDataByIdThunk } from "@/redux/thunks/getTDRChartDataByIdThunk";
import { getReferenceCurveBySlotThunk } from "@/redux/thunks/getReferenceCurveBySlotThunk"; // ⬅ import ergänzen
const TDRChartActionBar: React.FC = () => {
const dispatch = useAppDispatch();
@@ -91,10 +91,16 @@ const TDRChartActionBar: React.FC = () => {
// 📥 Beim Slot-Wechsel TDM-Liste + letzte ID laden
useEffect(() => {
if (selectedSlot !== null) {
dispatch(fetchTDMDataBySlotThunk(selectedSlot)).then((action: any) => {
const slotData = action.payload?.data;
if (slotData?.length > 0) {
const lastId = slotData[0].id;
dispatch(fetchTDMDataBySlotThunk(selectedSlot)).then((action) => {
// action can be a PayloadAction with payload or a rejected action
const payload = (
action as {
payload?: { data?: { id: number; t: string; d: number }[] };
}
).payload;
const slotData = payload?.data;
if ((slotData ?? []).length > 0) {
const lastId = (slotData ?? [])[0].id;
setSelectedId(lastId);
dispatch(getTDRChartDataByIdThunk(lastId));
}

View File

@@ -1,5 +1,5 @@
"use client"; // components/modules/kue705FO/Kue705FO.tsx
import React, { useState, useEffect, useRef, useMemo } from "react";
import React, { useState, useRef, useMemo } from "react";
import { useSelector } from "react-redux";
import KueModal from "./modals/SettingsModalWrapper";
import "bootstrap-icons/font/bootstrap-icons.css"; // Import Bootstrap Icons
@@ -9,14 +9,15 @@ import ChartSwitcher from "./Charts/ChartSwitcher";
import { RootState } from "../../../../redux/store";
import { useDispatch } from "react-redux";
//-------hooks----------------
import useChartPlugin from "./hooks/useChartPlugin";
import useAlarmStatus from "./hooks/useAlarmStatus";
import useKueVersion from "./hooks/useKueVersion";
import useIsoDisplay from "./hooks/useIsoDisplay";
import useLoopDisplay from "./hooks/useLoopDisplay";
import useModulName from "./hooks/useModulName";
import useChartData from "./hooks/useChartData";
import useTDRChart from "./hooks/useTDRChart";
import type { Chart } from "chart.js";
//--------handlers----------------
import handleButtonClick from "./kue705FO-Funktionen/handleButtonClick";
import handleOpenModal from "./handlers/handleOpenModal";
@@ -36,15 +37,10 @@ const Kue705FO: React.FC<Kue705FOProps> = ({
/* console.log(
`Rendering Kue705FO - SlotIndex: ${slotIndex}, ModulName: ${modulName}`
); */
const selectedChartData = useSelector(
(state: RootState) => state.selectedChartDataSlice.selectedChartData
);
const dispatch = useDispatch();
const { kueName } = useSelector((state: RootState) => state.kueDataSlice);
const chartRef = useRef(null);
const [activeButton, setActiveButton] = useState<"Schleife" | "TDR">(
"Schleife"
);
@@ -52,21 +48,17 @@ const Kue705FO: React.FC<Kue705FOProps> = ({
const [loopTitleText, setloopTitleText] = useState(
"Schleifenwiderstand [kOhm]"
);
const [isoDisplayText, setIsoDisplayText] = useState("Aderbruch");
const [groundFaultDisplayText, setGroundFaultDisplayText] =
useState("Erdschluss");
const [loopFaultDisplayText, setLoopFaultDisplayText] =
useState("Schleifenfehler");
const [isoFaultDisplayText, setIsoFaultDisplayText] =
useState("Isolationsfehler");
const [isoGreaterThan200, setIsoGreaterThan200] = useState(">200 MOhm");
const [isoDisplayText] = useState("Aderbruch");
const [groundFaultDisplayText] = useState("Erdschluss");
const [loopFaultDisplayText] = useState("Schleifenfehler");
const [isoFaultDisplayText] = useState("Isolationsfehler");
const [isoGreaterThan200] = useState(">200 MOhm");
const [loading, setLoading] = useState(false);
const [showModal, setShowModal] = useState(false);
const [showChartModal, setShowChartModal] = useState(false);
const [loopMeasurementCurveChartData, setLoopMeasurementCurveChartData] =
useState(null);
// Removed unused loopMeasurementCurveChartData state
//------- Redux-Variablen abrufen--------------------------------
const {
@@ -108,6 +100,9 @@ const Kue705FO: React.FC<Kue705FOProps> = ({
handleOpenChartModal(setShowChartModal, dispatch, slotIndex, activeButton);
const refreshClick = () =>
handleRefreshClick(activeButton, slotIndex, setLoading);
// Create a ref for the chart instance to pass as the second argument
const chartInstance = useRef<Chart | null>(null);
const closeChartModal = () =>
handleCloseChartModal(setShowChartModal, chartInstance);
//----------------------------------
@@ -122,23 +117,20 @@ const Kue705FO: React.FC<Kue705FOProps> = ({
);
const isoDisplayValue = useIsoDisplay(
slotIndex,
kuePSTmMinus96V,
kueCableBreak,
kueGroundFault,
kueAlarm1,
kueAlarm2,
kueOverflow,
isolationswert,
!!kuePSTmMinus96V?.[slotIndex],
!!kueCableBreak?.[slotIndex],
!!kueGroundFault?.[slotIndex],
!!kueAlarm1?.[slotIndex],
!!kueAlarm2?.[slotIndex],
!!kueOverflow?.[slotIndex],
Number(isolationswert),
isoDisplayText,
groundFaultDisplayText,
isoFaultDisplayText,
loopFaultDisplayText,
isoGreaterThan200
);
const { currentModulName, setCurrentModulName } = useModulName(
slotIndex,
modulName
);
const { setCurrentModulName } = useModulName(slotIndex, modulName);
//---------------------------------
//---------------------------------
const tdmChartData = useSelector(
@@ -167,9 +159,8 @@ const Kue705FO: React.FC<Kue705FOProps> = ({
loopValue,
activeButton
);
const zoomPlugin = useChartPlugin();
useChartData(loopMeasurementCurveChartData);
const { chartInstance } = useTDRChart(selectedChartData);
// Removed useChartData(loopMeasurementCurveChartData) as the state was unused
//---------------------------------
@@ -283,8 +274,8 @@ const Kue705FO: React.FC<Kue705FOProps> = ({
), // Hier sicherstellen, dass nur number übergeben wird
Number(schleifenwiderstand), // <- Stelle sicher, dass es eine Zahl ist
tdrLocation,
slotIndex,
dispatch
dispatch,
slotIndex
)
}
className={`w-[50%] h-[1.563rem] text-white text-[0.625rem] flex items-center justify-center ${

View File

@@ -2,12 +2,12 @@ import { Dispatch, SetStateAction } from "react";
// Funktion zur Änderung der Werte
const handleChange = (
setter: Dispatch<SetStateAction<any[]>>, // Typ für den Setter
setter: Dispatch<SetStateAction<string[]>>, // Typ für den Setter (z.B. string[])
e: React.ChangeEvent<HTMLInputElement>, // Typ für das Event
slot: number // Typ für den Slot
) => {
const value = e.target.value;
setter((prev: any[]) => {
setter((prev: string[]) => {
// Typ für den vorherigen Zustand
const updated = [...prev];
updated[slot] = value;

View File

@@ -1,7 +1,9 @@
// components/main/kabelueberwachung/kue705FO/handlers/handleCloseChartModal.ts
import { Chart } from "chart.js";
const handleCloseChartModal = (
setShowChartModal: (value: boolean) => void,
chartInstance: any
chartInstance: React.MutableRefObject<Chart | null>
) => {
if (chartInstance.current) {
console.log("Chart wird beim Schließen des Modals zerstört.");

View File

@@ -1,7 +1,7 @@
// components/main/kabelueberwachung/kue705FO/handlers/handleRefreshClick.ts
import { Dispatch, SetStateAction } from "react";
import { goLoop } from "../../../../../utils/goLoop";
import { goTDR } from "../../../../../utils/goTDR";
import { goLoop } from "@/utils/goLoop";
import { goTDR } from "@/utils/goTDR";
const handleRefreshClick = (
activeButton: "Schleife" | "TDR",

View File

@@ -32,13 +32,13 @@ export interface HandleSaveParams {
speicherintervall: number[];
};
slot: number;
dispatch: any;
dispatch: import("redux").Dispatch;
onModulNameChange: (id: string) => void;
onClose: () => void;
onFormUpdate?: (updated: any) => void; // Added this property
onFormUpdate?: (updated: Record<string, unknown>) => void; // Specify a more precise type instead of 'any'
}
const isDifferent = (a: any, b: any): boolean => {
const isDifferent = (a: unknown, b: unknown): boolean => {
const aNum = Number(a);
const bNum = Number(b);
if (!isNaN(aNum) && !isNaN(bNum)) {
@@ -62,7 +62,7 @@ const handleSave = async ({
onModulNameChange,
onClose,
}: HandleSaveParams): Promise<void> => {
const changesForFile: Record<string, any> = {};
const changesForFile: Record<string, string | number> = {};
if (isDifferent(ids[slot], originalValues.kueID[slot])) {
changesForFile.KID = ids[slot];

View File

@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { setSelectedChartData } from "../../../../../redux/slices/selectedChartDataSlice";
const useChartData = (loopMeasurementCurveChartData: any) => {
const useChartData = (loopMeasurementCurveChartData: unknown) => {
const dispatch = useDispatch();
useEffect(() => {

View File

@@ -1,9 +1,10 @@
// components/main/kabelueberwachung/kue705FO/hooks/useChartPlugin.ts
import { useState, useEffect } from "react";
import { Plugin } from "chart.js";
import Chart from "chart.js/auto";
const useChartPlugin = () => {
const [zoomPlugin, setZoomPlugin] = useState<any>(null);
const [zoomPlugin, setZoomPlugin] = useState<Plugin | null>(null);
useEffect(() => {
if (typeof window !== "undefined") {

View File

@@ -4,13 +4,13 @@ import { getAlarmDisplayText } from "../../../../../utils/alarmUtils";
const useIsoDisplay = (
slotIndex: number,
kuePSTmMinus96V: any,
kueCableBreak: any,
kueGroundFault: any,
kueAlarm1: any,
kueAlarm2: any,
kueOverflow: any,
isolationswert: any,
kuePSTmMinus96V: boolean,
kueCableBreak: boolean,
kueGroundFault: boolean,
kueAlarm1: boolean,
kueAlarm2: boolean,
kueOverflow: boolean,
isolationswert: number,
isoDisplayText: string,
groundFaultDisplayText: string,
isoFaultDisplayText: string,
@@ -25,12 +25,12 @@ const useIsoDisplay = (
setIsoDisplayValue(
getAlarmDisplayText(
slotIndex,
kuePSTmMinus96V,
kueCableBreak,
kueGroundFault,
kueAlarm1,
kueAlarm2,
kueOverflow ?? undefined,
[kuePSTmMinus96V ? 1 : 0],
[kueCableBreak ? 1 : 0],
[kueGroundFault ? 1 : 0],
[kueAlarm1 ? 1 : 0],
[kueAlarm2 ? 1 : 0],
[kueOverflow ? 1 : 0],
isolationswert,
isoDisplayText,
groundFaultDisplayText,

View File

@@ -1,7 +1,7 @@
// components/main/kabelueberwachung/kue705FO/hooks/useKueVersion.ts
import { useEffect, useState } from "react";
const useKueVersion = (slotIndex: number, reduxKueVersion: any) => {
const useKueVersion = (slotIndex: number, reduxKueVersion: number[]) => {
const [kueVersion, setKueVersion] = useState("V4.19");
useEffect(() => {

View File

@@ -1,27 +1,22 @@
// components/main/kabelueberwachung/kue705FO/hooks/useTDRChart.ts
import { useEffect, useRef } from "react";
import { useState, useEffect } from "react";
import Chart from "chart.js/auto";
import { createTDRChart } from "../../../../../utils/chartUtils";
const useTDRChart = (selectedChartData: any) => {
const chartInstance = useRef<Chart | null>(null);
type ZoomPluginType = { id: string } | null;
const useChartPlugin = () => {
const [zoomPlugin, setZoomPlugin] = useState<ZoomPluginType>(null);
useEffect(() => {
if (selectedChartData) {
createTDRChart(selectedChartData); // Neues Chart erstellen
if (typeof window !== "undefined") {
import("chartjs-plugin-zoom").then((mod) => {
setZoomPlugin(mod.default);
Chart.register(mod.default);
});
}
}, []);
return () => {
// Cleanup beim Komponentenwechsel
if (chartInstance.current) {
console.log("Chart wird beim Komponentenwechsel zerstört.");
chartInstance.current.destroy();
chartInstance.current = null;
}
};
}, [selectedChartData]);
return { chartInstance };
return zoomPlugin;
};
export default useTDRChart;
export default useChartPlugin;

View File

@@ -1,9 +1,10 @@
// components/main/kabelueberwachung/kue705FO/kue705FO-Funktionen/handleButtonClick.ts
import { Dispatch } from "react";
import { AppDispatch } from "@/redux/store";
import {
setActiveMode,
setSelectedSlot,
} from "../../../../../redux/slices/kueChartModeSlice";
} from "@/redux/slices/kueChartModeSlice";
const handleButtonClick = (
button: "Schleife" | "TDR",
@@ -12,8 +13,8 @@ const handleButtonClick = (
setLoopDisplayValue: Dispatch<React.SetStateAction<number | string>>,
schleifenwiderstand: number,
tdrLocation: number[] | undefined,
slotIndex: number,
dispatch: Dispatch<any>
dispatch: AppDispatch,
slotIndex: number
) => {
// 🔥 Speichert den gewählten Slot im Redux-Store
dispatch(setSelectedSlot(slotIndex));

View File

@@ -16,7 +16,7 @@ interface Props {
onClose?: () => void;
}
export default function Knotenpunkte({ slot, onClose }: Props) {
export default function Knotenpunkte({ slot }: Props) {
const [knotenNamen, setKnotenNamen] = useState<string[]>(Array(10).fill(""));
const [linienNamen, setLinienNamen] = useState<string[]>(Array(10).fill(""));
const [linienLaenge, setLinienLaenge] = useState<number[]>(Array(10).fill(0));

View File

@@ -1,6 +1,6 @@
"use client";
import { useState, useEffect } from "react";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import type { RootState } from "../../../../../redux/store";
import handleSave from "../handlers/handleSave";
@@ -29,7 +29,7 @@ const memoryIntervalOptions = [
export default function KueEinstellung({
slot,
showModal,
onClose = () => {},
onModulNameChange,
}: Props) {

View File

@@ -12,17 +12,24 @@ interface KueModalProps {
onModulNameChange: (id: string) => void;
}
declare global {
interface Window {
__lastKueTab?: "kue" | "tdr" | "knoten";
kabelModalOpen?: boolean;
}
}
export default function KueModal({ showModal, onClose, slot }: KueModalProps) {
const [activeTab, setActiveTab] = useState<"kue" | "tdr" | "knoten">(() => {
if (typeof window !== "undefined" && (window as any).__lastKueTab) {
return (window as any).__lastKueTab;
if (typeof window !== "undefined" && window.__lastKueTab) {
return window.__lastKueTab;
}
return "kue";
});
useEffect(() => {
if (typeof window !== "undefined") {
(window as any).__lastKueTab = activeTab;
window.__lastKueTab = activeTab;
}
}, [activeTab]);
@@ -68,13 +75,13 @@ export default function KueModal({ showModal, onClose, slot }: KueModalProps) {
<div className="flex justify-start bg-gray-100 space-x-2 p-2">
{[
{ label: "Allgemein", key: "kue" },
{ label: "TDR ", key: "tdr" },
{ label: "Knotenpunkte", key: "knoten" },
{ label: "Allgemein", key: "kue" as const },
{ label: "TDR ", key: "tdr" as const },
{ label: "Knotenpunkte", key: "knoten" as const },
].map(({ label, key }) => (
<button
key={key}
onClick={() => setActiveTab(key as any)}
onClick={() => setActiveTab(key)}
className={`px-4 py-1 rounded-t font-bold text-sm ${
activeTab === key
? "bg-white text-littwin-blue"

View File

@@ -1,11 +1,17 @@
"use client";
type TdrData = {
daempfung: string;
geschwindigkeit: string;
trigger: string;
};
declare global {
interface Window {
__tdrCache?: Record<string, { data: any; tdrActive: boolean }>;
__tdrCache?: Record<string, { data: TdrData; tdrActive: boolean }>;
}
}
import React, { useState, useEffect } from "react";
import React, { useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../../redux/store";

View File

@@ -2,11 +2,11 @@
import React, { useState, useEffect } from "react";
import { RootState } from "../../../redux/store";
import { useSelector } from "react-redux";
import handleClearDatabase from "./handlers/dbHandlers/handleClearDatabase";
import handleReboot from "./handlers/handleReboot";
import handleSetDateTime from "./handlers/handleSetDateTime";
import { useAdminAuth } from "./hooks/useAdminAuth";
import handleAdminLogin from "./handlers/handleAdminLogin";
// import { useAdminAuth } from "./hooks/useAdminAuth";
// import handleAdminLogin from "./handlers/handleAdminLogin";
import { useDispatch } from "react-redux";
import { AppDispatch } from "../../../redux/store";
import { getSystemSettingsThunk } from "../../../redux/thunks/getSystemSettingsThunk";
@@ -18,12 +18,7 @@ const GeneralSettings: React.FC = () => {
(state: RootState) => state.systemSettingsSlice
);
const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(true);
const [loginSuccess, setLoginSuccess] = useState(false);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
// const [error, setError] = useState("");
const [name, setName] = useState(systemSettings.deviceName || "");
const [mac1, setMac1] = useState(systemSettings.mac1 || "");
@@ -34,26 +29,14 @@ const GeneralSettings: React.FC = () => {
systemSettings.cplInternalTimestamp || ""
);
const handleLogin = async () => {
handleAdminLogin(
username,
password,
() => {
setLoginSuccess(true);
setError("");
},
(errorMsg) => {
setLoginSuccess(false);
setError(errorMsg);
},
dispatch
);
};
// Add loginSuccess state if you want to use it for feedback
// const [loginSuccess, setLoginSuccess] = useState(false);
useEffect(() => {
if (!systemSettings.deviceName) {
dispatch(getSystemSettingsThunk());
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/*
fix: Initialwerte in Allgemeine Einstellungen bei Seitenaufruf setzen
@@ -198,10 +181,7 @@ const GeneralSettings: React.FC = () => {
*/}
{/* Feedback */}
{loginSuccess && (
<p className="text-green-600 text-xs">Login erfolgreich!</p>
)}
{error && <p className="text-red-500 text-xs">{error}</p>}
{/* You can add feedback here if needed */}
{/* Buttons */}
<div className="col-span-2 flex flex-wrap md:justify-between gap-1 mt-2">

View File

@@ -1,30 +1,31 @@
"use client";
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { RootState } from "../../../redux/store";
import handleNtpSubmit from "./handlers/handleNtpSubmit";
const NTPSettings: React.FC = () => {
const dispatch = useDispatch();
const systemSettings = useSelector(
(state: RootState) => state.systemSettingsSlice
);
// Lokale States mit Fallback-Werten absichern
const [ntp1, setNtp1] = React.useState(systemSettings?.ntp1 ?? "");
const [ntp2, setNtp2] = React.useState(systemSettings?.ntp2 ?? "");
const [ntp3, setNtp3] = React.useState(systemSettings?.ntp3 ?? "");
const [ntpTimezone, setNtpTimezone] = React.useState(
systemSettings?.ntpTimezone ?? ""
);
const [active, setActive] = React.useState(
systemSettings?.ntpActive ?? false
);
// Wenn Daten noch nicht geladen sind, Ladeanzeige anzeigen
if (!systemSettings || systemSettings.ntp1 === undefined) {
return <p className="text-xs text-gray-500">Lade NTP-Daten...</p>;
}
// Lokale States mit Fallback-Werten absichern
const [ntp1, setNtp1] = React.useState(systemSettings.ntp1 ?? "");
const [ntp2, setNtp2] = React.useState(systemSettings.ntp2 ?? "");
const [ntp3, setNtp3] = React.useState(systemSettings.ntp3 ?? "");
const [ntpTimezone, setNtpTimezone] = React.useState(
systemSettings.ntpTimezone ?? ""
);
const [active, setActive] = React.useState(systemSettings.ntpActive ?? false);
return (
<div className="p-6 md:p-3 bg-gray-100 max-w-5xl mr-auto">
<h2 className="text-sm md:text-md font-bold mb-4">NTP Einstellungen</h2>

View File

@@ -1,14 +1,9 @@
"use client"; // /components/main/settingsPageComponents/OPCUAInterfaceSettings.tsx
import React, { useState } from "react";
import Image from "next/image";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../redux/store";
import {
setOpcUaEncryption,
toggleOpcUaServer,
setOpcUaNodesetName,
addOpcUaUser,
removeOpcUaUser,
} from "../../../redux/slices/opcuaSettingsSlice";
import { toggleOpcUaServer } from "../../../redux/slices/opcuaSettingsSlice";
export default function OPCUAInterfaceSettings() {
const dispatch = useDispatch();
@@ -17,29 +12,28 @@ export default function OPCUAInterfaceSettings() {
);
// Lokale Zustände für das neue Benutzerformular
const [newUsername, setNewUsername] = useState("");
const [newPassword, setNewPassword] = useState("");
const [nodesetName, setNodesetName] = useState(
opcuaSettings.opcUaNodesetName
);
const handleAddUser = () => {
if (newUsername.trim() && newPassword.trim()) {
dispatch(addOpcUaUser({ username: newUsername, password: newPassword }));
setNewUsername("");
setNewPassword("");
}
};
const handleNodesetUpdate = () => {
dispatch(setOpcUaNodesetName(nodesetName));
};
return (
<div className="p-6 md:p-3 bg-gray-100 max-w-5xl mr-auto ">
<div className="flex justify-between items-center mb-3">
<h2 className="text-base font-semibold">OPCUA Server Einstellungen</h2>
<img src="/images/OPCUA.jpg" alt="OPCUA Logo" className="h-12 w-auto" />
<Image
src="/images/OPCUA.jpg"
alt="OPCUA Logo"
width={48}
height={48}
className="h-12 w-auto"
/>
<Image
src="/images/OPCUA.jpg"
alt="OPCUA Logo"
width={48}
height={48}
className="h-12 w-auto"
/>
</div>
{/* ✅ Server Aktivierung */}

View File

@@ -2,14 +2,15 @@
import bcrypt from "bcryptjs";
import { generateToken } from "../utils/cryptoUtils";
import USERS from "../config/users";
import { setAdminLoggedIn } from "../../../../redux/slices/authSlice"; // ✅ Wichtig
import { setAdminLoggedIn } from "@/redux/slices/authSlice"; // ✅ Wichtig
import { AppDispatch } from "@/redux/store"; // Import your AppDispatch type
const handleAdminLogin = (
username: string,
password: string,
onSuccess: () => void,
onError: (errorMsg: string) => void,
dispatch: any // ✅ neu
onError: (message: string) => void,
dispatch: AppDispatch // Use the correct dispatch type
) => {
const user = USERS.Admin;
bcrypt.compare(password, user.password, (err, isMatch) => {

View File

@@ -16,7 +16,6 @@ const handleGeneralSubmit = (
) => {
const changes: { [key: string]: string } = {};
let networkChanges = false;
let newIp: string | null = null;
if (current.name !== original.name) {
changes.SNNA = current.name;
@@ -24,7 +23,6 @@ const handleGeneralSubmit = (
}
if (current.ip !== original.ip) {
changes.SEI01 = current.ip;
newIp = current.ip;
networkChanges = true;
}
if (current.subnet !== original.subnet) {

View File

@@ -2,9 +2,9 @@
import React, { useMemo, useEffect } from "react";
import { useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import { RootState, useAppDispatch } from "../../../redux/store";
import { RootState, useAppDispatch } from "@/redux/store";
import KabelModulStatus from "./modulesStatus/KabelModulStatus";
import { getKueDataThunk } from "../../../redux/thunks/getKueDataThunk";
import { getKueDataThunk } from "@/redux/thunks/getKueDataThunk";
const Baugruppentraeger: React.FC = () => {
const dispatch = useAppDispatch();

View File

@@ -33,7 +33,7 @@ const Last20MessagesTable: React.FC<{ className?: string }> = ({
window.location.hostname === "localhost";
const url = isDev
? `/api/cpl/messages?MSS1=${from};${to};All`
? `/api/cpl/last20MessagesAPIHandler`
: `/CPL?Service/ae.ACP&MSS1=${from};${to};All`;
try {

View File

@@ -1,9 +1,10 @@
"use client"; //components/main/uebersicht/NetworkInfo.tsx
import React, { useEffect } from "react";
import Image from "next/image";
import { useSelector, useDispatch } from "react-redux";
import { RootState, AppDispatch } from "../../../redux/store";
import { getSystemSettingsThunk } from "../../../redux/thunks/getSystemSettingsThunk";
import { getOpcUaSettingsThunk } from "../../../redux/thunks/getOpcUaSettingsThunk";
import { RootState, AppDispatch } from "@/redux/store";
import { getSystemSettingsThunk } from "@/redux/thunks/getSystemSettingsThunk";
import { getOpcUaSettingsThunk } from "@/redux/thunks/getOpcUaSettingsThunk";
const NetworkInfo: React.FC = () => {
const dispatch: AppDispatch = useDispatch();
@@ -26,10 +27,7 @@ const NetworkInfo: React.FC = () => {
const opcUaZustandRaw = useSelector(
(state: RootState) => state.opcuaSettingsSlice.opcUaZustand
);
const opcUaNodesetName =
useSelector(
(state: RootState) => state.opcuaSettingsSlice.opcUaNodesetName
) || "Unbekannt";
// OPC-UA Zustand in lesbaren Text umwandeln
const opcUaZustand =
Number(opcUaZustandRaw) === 1
@@ -41,11 +39,13 @@ const NetworkInfo: React.FC = () => {
return (
<div className="w-full flex-direction: row flex">
<div className=" flex-grow flex justify-between items-center mt-1 bg-white p-2 rounded-lg shadow-md border border-gray-200 laptop:m-0 laptop:scale-y-75 2xl:scale-y-75">
<div className="flex items-center space-x-4">
<img
<Image
src="/images/IP-icon.svg"
alt="IP Address"
width={24}
height={24}
className="w-6 text-littwin-blue"
priority
/>
<div>
<p className="text-xs text-gray-500">IP-Adresse</p>
@@ -54,10 +54,13 @@ const NetworkInfo: React.FC = () => {
</div>
<div className="flex items-center space-x-4">
<img
<Image
src="/images/subnet-mask.svg"
alt="subnet mask"
width={24}
height={24}
className="w-6"
priority
/>
<div>
<p className="text-xs text-gray-500">Subnet-Maske</p>
@@ -66,7 +69,14 @@ const NetworkInfo: React.FC = () => {
</div>
<div className="flex items-center space-x-4">
<img src="/images/gateway.svg" alt="gateway" className="w-6" />
<Image
src="/images/gateway.svg"
alt="gateway"
width={24}
height={24}
className="w-6"
priority
/>
<div>
<p className="text-xs text-gray-500">Gateway</p>
<p className="text-sm font-medium text-gray-700">{gateway}</p>
@@ -92,7 +102,6 @@ const NetworkInfo: React.FC = () => {
</div>
*/}
</div>
</div>
);
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

@@ -36,7 +36,7 @@
"win_de_invert": [
0,
0,
1,
0,
0,
0,
0,
@@ -104,7 +104,7 @@
"win_de_time_filter": [
2,
0,
0,
1,
0,
0,
0,
@@ -138,7 +138,7 @@
"win_de_weighting": [
4,
0,
0,
1,
0,
0,
0,
@@ -238,7 +238,7 @@
0
],
"win_de_label": [
"DE114",
"DE11",
"DE2",
"DE3",
"DE4",

View File

@@ -1,6 +1,6 @@
{
"win_da_state": [
1,
0,
0,
0,
1

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "cpl-v4",
"version": "1.6.482",
"version": "1.6.483",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cpl-v4",
"version": "1.6.482",
"version": "1.6.483",
"dependencies": {
"@fontsource/roboto": "^5.1.0",
"@iconify-icons/ri": "^1.2.10",

View File

@@ -1,6 +1,6 @@
{
"name": "cpl-v4",
"version": "1.6.482",
"version": "1.6.483",
"private": true,
"scripts": {
"dev": "next dev",

View File

@@ -5,7 +5,6 @@ import { useEffect, useState } from "react";
import { Provider } from "react-redux";
import store, { useAppDispatch } from "@/redux/store";
import { AppProps } from "next/app";
import { loadWindowVariables } from "@/utils/loadWindowVariables";
import Header from "@/components/header/Header";
import Navigation from "@/components/navigation/Navigation";
@@ -43,7 +42,7 @@ function AppContent({
pageProps: AppProps["pageProps"];
}): JSX.Element {
const dispatch = useAppDispatch();
const [sessionExpired, setSessionExpired] = useState(false);
const [sessionExpired] = useState(false);
const mode = "DIA0"; // oder aus Router oder Session
const type = 0; // Beispiel: 0 für "loop", 1 für "iso" (bitte ggf. anpassen)
useEffect(() => {
@@ -93,7 +92,7 @@ function AppContent({
intervalId = setInterval(loadAndDispatch, 10000);
return () => clearInterval(intervalId);
}
}, []);
}, [dispatch]);
return (
<div className="flex flex-col h-screen overflow-hidden">

View File

@@ -1,14 +1,23 @@
"use client"; ///pages/analogeEingaenge.tsx
import React, { useState, useEffect } from "react";
import AnalogInputsTable from "../components/main/analogInputs/AnalogInputsTable";
import AnalogInputsChart from "../components/main/analogInputs/AnalogInputsChart";
import AnalogInputsSettingsModal from "../components/main/analogInputs/AnalogInputsSettingsModal";
import { getAnalogInputsThunk } from "../redux/thunks/getAnalogInputsThunk";
import { useAppDispatch } from "../redux/store";
import AnalogInputsTable from "@/components/main/analogInputs/AnalogInputsTable";
import AnalogInputsChart from "@/components/main/analogInputs/AnalogInputsChart";
import AnalogInputsSettingsModal from "@/components/main/analogInputs/AnalogInputsSettingsModal";
import { getAnalogInputsThunk } from "@/redux/thunks/getAnalogInputsThunk";
import { useAppDispatch } from "@/redux/store";
export interface AnalogInput2 {
id: number;
label?: string;
offset?: number | string;
factor?: number | string;
loggerInterval: string;
unit?: string;
}
function AnalogInputs() {
const [selectedId, setSelectedId] = useState<number | null>(null);
const [selectedInput, setSelectedInput] = useState<any | null>(null);
const [selectedInput, setSelectedInput] = useState<AnalogInput2 | null>(null);
const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
const dispatch = useAppDispatch();
@@ -32,7 +41,9 @@ function AnalogInputs() {
</h2>
<AnalogInputsTable
setSelectedId={setSelectedId}
setSelectedInput={setSelectedInput}
setSelectedInput={(input) =>
setSelectedInput(input as unknown as AnalogInput2)
}
setIsSettingsModalOpen={setIsSettingsModalOpen}
/>
</div>
@@ -46,11 +57,13 @@ function AnalogInputs() {
</div>
</div>
{selectedInput !== null && (
<AnalogInputsSettingsModal
selectedInput={selectedInput}
isOpen={isSettingsModalOpen}
onClose={() => setIsSettingsModalOpen(false)}
/>
)}
</div>
);
}

View File

@@ -9,7 +9,7 @@ export default async function handler(
res: NextApiResponse
) {
try {
const result: Record<number, any[]> = {};
const result: Record<number, unknown[]> = {};
for (let i = 1; i <= 8; i++) {
const filePath = path.join(
@@ -22,10 +22,11 @@ export default async function handler(
try {
const fileContent = await fs.readFile(filePath, "utf-8");
result[99 + i] = JSON.parse(fileContent); // z.B. 100 für AE1, 101 für AE2
} catch (err) {
result[99 + i] = JSON.parse(fileContent); // z. B. 100 für AE1, 101 für AE2
} catch (error) {
console.warn(
`Mock-Datei für analogInput${i} nicht gefunden oder fehlerhaft.`
`Mock-Datei für analogInput${i} nicht gefunden oder fehlerhaft.`,
error
);
result[99 + i] = [];
}

View File

@@ -1,4 +1,4 @@
// /pages/api/cpl/getDigitalOutputsJsonHandler.ts
// /pages/api/cpl/getDigitalOutputsHandler.ts
import { NextApiRequest, NextApiResponse } from "next";
import path from "path";
@@ -12,7 +12,7 @@ export default async function handler(
const mode = process.env.NEXT_PUBLIC_CPL_MODE ?? "json";
if (mode === "json") {
// Lese JSON-Datei z.B. digitalOutputsMockData.json
// Lese JSON-Datei z.B. digitalOutputsMockData.json
const filePath = path.join(
process.cwd(),
"mocks/api/SERVICE/digitalOutputsMockData.json"

View File

@@ -20,6 +20,10 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data);
} catch (error) {
res.status(404).json({ error: "File not found" });
console.error(
"Fehler bei der Verarbeitung von kabelueberwachungAPIHandler:",
error
);
res.status(500).json({ error: "Interner Serverfehler" });
}
}

View File

@@ -21,6 +21,7 @@ export default async function handler(
res.setHeader("Content-Type", "text/javascript"); // wichtig!
res.status(200).send(data);
} catch (error) {
res.status(404).json({ error: "File not found" });
console.error("Fehler beim Laden der letzten 20 Meldungen:", error);
res.status(500).json({ error: "Interner Serverfehler" });
}
}

View File

@@ -6,6 +6,13 @@ import { promises as fs } from "fs";
function parseDate(str: string): Date {
return new Date(str.replace(" ", "T"));
}
export type Message = {
id: number;
timestamp: string;
text: string;
level: string;
// oder alles, was dein `result` konkret enthält
};
export default async function handler(
req: NextApiRequest,
@@ -38,8 +45,8 @@ export default async function handler(
}
if (fromDate && toDate) {
const filtered = data.filter((msg: any) => {
const messageDate = parseDate(msg.t);
const filtered = data.filter((msg: Message) => {
const messageDate = parseDate(msg.timestamp);
return messageDate >= fromDate! && messageDate <= toDate!;
});

View File

@@ -20,6 +20,7 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data);
} catch (error) {
console.error("Error processing opcuaAPIHandler:", error);
res.status(404).json({ error: "File not found" });
}
}

View File

@@ -3,10 +3,24 @@ import { NextApiRequest, NextApiResponse } from "next";
import path from "path";
import fs from "fs/promises";
// Typ für einzelne Einträge im JSON-Array
type ChartDataEntry = {
timestamp?: string;
zeit?: string;
time?: string;
[key: string]: unknown; // zusätzliche Werte erlaubt
};
// Hilfsfunktion: JSON-Datei laden
async function loadJsonData(filePath: string) {
async function loadJsonData(filePath: string): Promise<ChartDataEntry[]> {
const data = await fs.readFile(filePath, "utf8");
return JSON.parse(data);
const parsed = JSON.parse(data);
if (!Array.isArray(parsed)) {
throw new Error("Ungültiges Format: Erwartet ein Array");
}
return parsed;
}
export default async function handler(
@@ -32,20 +46,23 @@ export default async function handler(
try {
const jsonData = await loadJsonData(jsonFilePath);
// Filtern nach Datum, wenn angegeben
let filteredData = jsonData;
if (vonDatum && bisDatum) {
const von = new Date(`${vonDatum}T00:00:00`);
const bis = new Date(`${bisDatum}T23:59:59`);
filteredData = jsonData.filter((item: any) => {
const timestamp = new Date(item.t);
return timestamp >= von && timestamp <= bis;
filteredData = jsonData.filter((item) => {
const dateString = item.timestamp ?? item.zeit ?? item.time;
const itemDate = dateString ? new Date(dateString) : null;
return itemDate !== null && itemDate >= von && itemDate <= bis;
});
}
return res.status(200).json(filteredData);
res.status(200).json(filteredData);
} catch (error) {
return res.status(404).json({ error: "File not found or read error" });
console.error("Fehler beim Lesen der Slot-Daten:", error);
res.status(500).json({ error: "Fehler beim Lesen der Slot-Daten" });
}
}

View File

@@ -20,6 +20,7 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data);
} catch (error) {
console.error("Error processing systemAPIHandler:", error);
res.status(404).json({ error: "File not found" });
}
}

View File

@@ -20,6 +20,7 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data);
} catch (error) {
console.error("Error processing systemVoltTempAPIHandler:", error);
res.status(404).json({ error: "File not found" });
}
}

View File

@@ -26,6 +26,7 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8");
res.status(200).json(JSON.parse(data));
} catch (error) {
console.error("Error processing tdmDataAPIHandler:", error);
res.status(404).json({ error: "File not found" });
}
}

View File

@@ -26,6 +26,7 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8");
res.status(200).json(JSON.parse(data));
} catch (error) {
console.error("Error processing tdrDataAPIHandler:", error);
res.status(404).json({ error: "File not found" });
}
}

View File

@@ -21,6 +21,7 @@ export default async function handler(
const fileContent = await fs.readFile(filePath, "utf-8");
res.status(200).json(JSON.parse(fileContent));
} catch (error) {
console.error("Error processing tdrReferenceCurveAPIHandler:", error);
res.status(404).json({ error: "File not found" });
}
}

View File

@@ -34,7 +34,6 @@ if (!mockFilePath) {
// Funktion zum Parsen bei jsSimulatedProd
function extractMockData(raw: string) {
const context = {};
const func = new Function(
"context",
`
@@ -81,11 +80,9 @@ export default async function handler(
const rawContent = fs.readFileSync(mockFilePath!, "utf-8");
// 3⃣ JSON vs JS Verarbeitung
const data =
mode === "json" ? JSON.parse(rawContent) : extractMockData(rawContent);
// 4⃣ Aktualisieren der Felder
if (typeof label === "string") data.win_de_label[id - 1] = label;
if (typeof invert === "number") data.win_de_invert[id - 1] = invert;
if (typeof timeFilter === "number")
@@ -97,7 +94,6 @@ export default async function handler(
if (typeof eingangOffline === "number")
data.win_de_offline[id - 1] = eingangOffline;
// 5⃣ Speichern
if (mode === "json") {
fs.writeFileSync(mockFilePath!, JSON.stringify(data, null, 2), "utf-8");
} else {
@@ -128,8 +124,12 @@ var win_de_label = ${JSON.stringify(data.win_de_label, null, 2)};
weighting,
eingangOffline,
});
} catch (err: any) {
console.error("Fehler beim Schreiben:", err);
} catch (err: unknown) {
if (err instanceof Error) {
console.error("Fehler beim Schreiben:", err.message);
} else {
console.error("Unbekannter Fehler beim Schreiben:", err);
}
return res.status(500).json({ error: "Update fehlgeschlagen" });
}
}

View File

@@ -6,7 +6,7 @@ export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
let { key, value, slot } = req.query;
const { key, value, slot } = req.query;
if (
typeof key !== "string" ||

View File

@@ -29,6 +29,7 @@ export default async function handler(
await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
res.status(200).json({ success: true });
} catch (error) {
console.error("Error processing updateTdrReferenceCurveAPIHandler:", error);
res.status(500).json({ error: "Failed to save file" });
}
}

View File

@@ -32,7 +32,7 @@ export default async function handler(
}
const arrayRaw = match[0].match(/\[(.*)\]/s)?.[1] || "";
let values = arrayRaw
const values = arrayRaw
.split(",")
.map((v) => v.trim())
.map((v) => (v === "" ? "0" : v))
@@ -45,10 +45,7 @@ export default async function handler(
}
// Bereinige kaputte Endzeilen wie ")"
fileContent = fileContent.replace(
/^\s*[\)\(a-zA-Z0-9\/\:\. ]{2,40}\s*$/gm,
""
);
fileContent = fileContent.replace(/^\s*[)(a-zA-Z0-9/:. ]{2,40}\s*$/gm, "");
await fs.writeFile(filePath, fileContent, "utf-8");

View File

@@ -1,6 +1,5 @@
"use client"; //pages/dashboard.tsx
import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import "tailwindcss/tailwind.css";
import "@fontsource/roboto";
import "bootstrap-icons/font/bootstrap-icons.css";

View File

@@ -1,43 +1,40 @@
"use client";
// /pages/digitalInputs.tsx
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../redux/store";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";
import InputModal from "../components/main/einausgaenge/modals/InputModal";
import InputModal from "@/components/main/einausgaenge/modals/InputModal";
import { getDigitalInputsThunk } from "@/redux/thunks/getDigitalInputsThunk";
import { getDigitalOutputsThunk } from "../redux/thunks/getDigitalOutputsThunk";
import DigitalInputs from "../components/main/einausgaenge/DigitalInputs";
import DigitalInputs from "@/components/main/einausgaenge/DigitalInputs";
const EinAusgaenge: React.FC = () => {
const dispatch = useDispatch<AppDispatch>();
const digitalInputs = useSelector(
(state: RootState) => state.digitalInputsSlice.inputs
);
const digitalOutputs = useSelector(
(state: RootState) => state.digitalOutputsSlice.outputs
);
interface DigitalInput {
id: number;
eingangOffline: boolean;
status: boolean;
label: string;
[key: string]: unknown;
}
const [selectedInput, setSelectedInput] = useState<DigitalInput | null>(null);
const [selectedInput, setSelectedInput] = useState(null);
const [selectedOutput, setSelectedOutput] = useState(null);
const [isInputModalOpen, setIsInputModalOpen] = useState(false);
const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);
useEffect(() => {
dispatch(getDigitalInputsThunk());
dispatch(getDigitalOutputsThunk());
const interval = setInterval(() => {
dispatch(getDigitalInputsThunk());
dispatch(getDigitalOutputsThunk());
}, 10000);
return () => clearInterval(interval);
}, [dispatch]);
const openInputModal = (input: any) => {
const openInputModal = (input: DigitalInput) => {
setSelectedInput(input);
setIsInputModalOpen(true);
};
@@ -47,16 +44,6 @@ const EinAusgaenge: React.FC = () => {
setIsInputModalOpen(false);
};
const openOutputModal = (output: any) => {
setSelectedOutput(output);
setIsOutputModalOpen(true);
};
const closeOutputModal = () => {
setSelectedOutput(null);
setIsOutputModalOpen(false);
};
return (
<div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)] laptop:h-[calc(100vh-10vh-5vh)] xl:h-[calc(100vh-10vh-6vh)] laptop:gap-0">
<h1 className="text-base font-semibold mb-2">Meldungseingänge</h1>

View File

@@ -1,23 +1,22 @@
"use client"; // /pages/digitalOutputs.tsx
"use client";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "@/redux/store";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";
import DigitalOutputsModal from "../components/main/einausgaenge/modals/DigitalOutputsModal";
import DigitalOutputs from "../components/main/einausgaenge/DigitalOutputsWidget";
import { getDigitalInputsThunk } from "@/redux/thunks/getDigitalInputsThunk";
import { getDigitalOutputsThunk } from "@/redux/thunks/getDigitalOutputsThunk";
import DigitalOutputs from "../components/main/einausgaenge/DigitalOutputsWidget";
import type { DigitalOutput } from "@/types/digitalOutput";
const EinAusgaenge: React.FC = () => {
const dispatch = useDispatch<AppDispatch>();
const digitalOutputs = useSelector(
(state: RootState) => state.digitalOutputsSlice.outputs
const [selectedOutput, setSelectedOutput] = useState<DigitalOutput | null>(
null
);
const [selectedOutput, setSelectedOutput] = useState(null);
const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);
useEffect(() => {
@@ -31,7 +30,7 @@ const EinAusgaenge: React.FC = () => {
return () => clearInterval(interval);
}, [dispatch]);
const openOutputModal = (output: any) => {
const openOutputModal = (output: DigitalOutput) => {
setSelectedOutput(output);
setIsOutputModalOpen(true);
};
@@ -49,12 +48,13 @@ const EinAusgaenge: React.FC = () => {
<DigitalOutputs openOutputModal={openOutputModal} />
</div>
{/* ✅ Modal aktiv einbinden */}
{selectedOutput && (
<DigitalOutputsModal
selectedOutput={selectedOutput}
isOpen={isOutputModalOpen}
closeOutputModal={closeOutputModal}
/>
)}
</div>
);
};

View File

@@ -1,6 +1,6 @@
"use client"; // /pages/kabelueberwachung.tsx
import React, { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useSearchParams } from "next/navigation";
import Kue705FO from "../components/main/kabelueberwachung/kue705FO/Kue705FO";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "../redux/store"; // Adjust the path to your Redux store file
@@ -10,10 +10,10 @@ import { getKueDataThunk } from "../redux/thunks/getKueDataThunk";
function Kabelueberwachung() {
const dispatch: AppDispatch = useDispatch();
const searchParams = useSearchParams(); // URL-Parameter holen
const initialRack = parseInt(searchParams.get("rack")) || 1; // Rack-Nummer aus URL oder 1
const initialRack = parseInt(searchParams.get("rack") ?? "1") || 1; // Rack-Nummer aus URL oder 1
const [activeRack, setActiveRack] = useState(initialRack); // Nutze initialRack als Startwert
const [alarmStatus, setAlarmStatus] = useState([]); // Alarmstatus
const [activeRack, setActiveRack] = useState<number>(initialRack); // Nutze initialRack als Startwert
const [alarmStatus, setAlarmStatus] = useState<boolean[]>([]); // Alarmstatus
// Redux-Variablen aus dem Store abrufen
const {
@@ -25,53 +25,51 @@ function Kabelueberwachung() {
kueResidence,
kueCableBreak,
kueGroundFault,
} = useSelector((state) => state.kueDataSlice);
//----------------------------------------------------------------
// 🚀 **TDR-Daten bereits in Redux abrufen**
// Redux-Variablen abrufen
const tdrData = useSelector((state) => state.tdrChartSlice.data);
const loading = useSelector((state) => state.tdrChartSlice.loading);
const error = useSelector((state) => state.tdrChartSlice.error);
//----------------------------------------------------------------
} = useSelector((state: RootState) => state.kueDataSlice);
//----------------------------------------------------------------
// Alarmstatus basierend auf Redux-Variablen berechnen
const updateAlarmStatus = () => {
const updatedAlarmStatus = kueIso.map((_, index) => {
return (
const updateAlarmStatus = React.useCallback(() => {
const updatedAlarmStatus = kueIso.map(
(_: number | string, index: number) => {
return Boolean(
(kueAlarm1 && kueAlarm1[index]) ||
(kueAlarm2 && kueAlarm2[index]) ||
(kueCableBreak && kueCableBreak[index]) ||
(kueGroundFault && kueGroundFault[index])
);
});
}
);
setAlarmStatus(updatedAlarmStatus);
};
}, [kueIso, kueAlarm1, kueAlarm2, kueCableBreak, kueGroundFault]);
// Alarmstatus initial berechnen und alle 10 Sekunden aktualisieren
useEffect(() => {
updateAlarmStatus();
const interval = setInterval(updateAlarmStatus, 10000);
return () => clearInterval(interval);
}, [kueIso, kueAlarm1, kueAlarm2, kueCableBreak, kueGroundFault]);
}, [updateAlarmStatus]);
// Modul- und Rack-Daten aufbereiten
const allModules = kueIso.map((iso, index) => ({
const allModules = kueIso.map((iso: number | string, index: number) => ({
isolationswert: iso,
schleifenwiderstand: kueResidence[index],
modulName: kueID[index] || `Modul ${index + 1}`, // Eindeutiger Name pro Index
kueOnlineStatus: kueOnline[index],
alarmStatus: alarmStatus[index],
tdrLocation: [], // Placeholder, replace with actual tdrLocation if available
}));
//console.log("Alle Module:", allModules);
const racks = {
const racks = React.useMemo(
() => ({
rack1: allModules.slice(0, 8),
rack2: allModules.slice(8, 16),
rack3: allModules.slice(16, 24),
rack4: allModules.slice(24, 32),
};
}),
[allModules]
);
// Konsolenausgaben für jede Rack-Aufteilung
/* console.log(
@@ -92,7 +90,7 @@ function Kabelueberwachung() {
); */
// Funktion zum Wechseln des Racks
const changeRack = (rack) => {
const changeRack = (rack: number) => {
setActiveRack(rack);
console.log(`Aktives Rack geändert zu: ${rack}`);
};
@@ -101,20 +99,11 @@ function Kabelueberwachung() {
/* console.log(`Aktives Rack: ${activeRack}`);
console.log(
`Rack ${activeRack} Modulnamen:`,
racks[`rack${activeRack}`].map((slot) => slot.modulName)
racks[`rack${activeRack as 1 | 2 | 3 | 4}` as keyof typeof racks].map((slot: any) => slot.modulName)
); */
}, [activeRack, racks]);
//-----------------------------------------------------------
const {
data: loopData,
loading: loopLoading,
error: loopError,
} = useSelector((state: RootState) => state.loopChartSlice);
// Zugriff z.B. auf Schleifenwiderstand von DIA1
const dia1Schleifen = loopData["DIA1"]?.[4];
const dia0Iso = loopData["DIA0"]?.[3];
//------------------------------------------------------------
useEffect(() => {
@@ -122,13 +111,12 @@ function Kabelueberwachung() {
console.log("📦 Lade KUE-Daten aus getKueDataThunk...");
dispatch(getKueDataThunk());
}
}, []);
}, [dispatch, kueIso.length]);
//------------------------------------------------------------
//----------------------------------------------------------------
// JSX rendering
return (
<div className="bg-gray-100 flex-1 p-6 text-black xl:p-4 2xl:p-6 h-[calc(100vh-13vh-8vh)]">
<h1 className="text-2xl xl:text-xl mb-4">Kabelüberwachung</h1>
<div>
<div className="mb-4">
{[1, 2, 3, 4].map((rack) => (
<button
@@ -145,7 +133,22 @@ function Kabelueberwachung() {
))}
</div>
<div className="flex flex-row space-x-8 xl:space-x-0 2xl:space-x-8 qhd:space-x-16 ml-[5%] mt-[5%]">
{racks[`rack${activeRack}`].map((slot, index) => {
{(
racks[
`rack${activeRack as 1 | 2 | 3 | 4}` as keyof typeof racks
] as typeof allModules
).map(
(
slot: {
isolationswert: number | string;
schleifenwiderstand: number | string;
modulName: string;
kueOnlineStatus: number;
alarmStatus?: boolean;
tdrLocation: number[];
},
index: number
) => {
const slotIndex = index + (activeRack - 1) * 8;
return (
<div key={index} className="flex">
@@ -156,10 +159,12 @@ function Kabelueberwachung() {
kueOnline={slot.kueOnlineStatus}
alarmStatus={slot.alarmStatus}
slotIndex={slotIndex}
tdrLocation={slot.tdrLocation}
/>
</div>
);
})}
}
)}
</div>
</div>
);

View File

@@ -1,7 +1,7 @@
"use client";
// /pages/meldungen.tsx
import React, { useState, useEffect } from "react";
import DateRangePickerMeldungen from "../components/main/meldungen/DateRangePickerMeldungen";
import DateRangePickerMeldungen from "@/components/main/meldungen/DateRangePickerMeldungen";
type Meldung = {
t: string;
@@ -41,7 +41,7 @@ export default function Messages() {
typeof window !== "undefined" && window.location.hostname === "localhost";
//http://10.10.0.118/CPL?Service/empty.ACP&MSS1=2025;06;01;2025;06;26;All
const url = isDev
? `/api/cpl/messages?MSS1=${fy};${fm};${fd};${ty};${tm};${td};All`
? `/api/cpl/messages`
: `/CPL?Service/ae.ACP&MSS1=${fy};${fm};${fd};${ty};${tm};${td};All`;
try {
@@ -67,6 +67,7 @@ export default function Messages() {
// einmal beim laden de Seite die Meldungen abrufen
useEffect(() => {
fetchMessages();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (

View File

@@ -12,6 +12,7 @@ import {
Title,
Tooltip,
Legend,
TooltipItem,
} from "chart.js";
import { Line } from "react-chartjs-2";
@@ -124,7 +125,7 @@ const SystemPage = () => {
},
tooltip: {
callbacks: {
label: function (context: any) {
label: function (context: TooltipItem<"line">) {
const label = context.dataset.label || "";
const value =
context.parsed.y !== null ? context.parsed.y.toFixed(2) : "";

View File

@@ -8,9 +8,10 @@ export interface AnalogInputsState {
// Standardwerte für Eingänge
const defaultAnalogInput: AnalogInput = {
id: null,
value: null,
id: 0,
value: 0,
label: "",
name: "",
uW: false,
uG: false,
oW: false,
@@ -37,13 +38,14 @@ export const loadFromWindow = createAsyncThunk(
for (let i = 1; i <= 8; i++) {
const key = `win_analogInputs${i}`;
const value = (window as any)[key];
const value = (window as unknown as { [key: string]: unknown })[key];
if (Array.isArray(value) && value.length === 7) {
data[key] = {
id: value[0],
value: value[1],
label: value[2],
name: "", // or set to value[2] or another appropriate value
uW: value[3] === 1,
uG: value[4] === 1,
oW: value[5] === 1,

View File

@@ -1,35 +1,29 @@
// /redux/slices/selectedAnalogInputSlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
export interface SelectedAnalogInput {
type SelectedAnalogInput = {
id: number;
label: string;
unit?: string;
value?: number;
offset?: number;
factor?: number;
loggerInterval?: number;
weighting?: number;
}
status: boolean;
loggerInterval: number;
};
const initialState: SelectedAnalogInput | null = null;
const selectedAnalogInputSlice = createSlice({
// @ts-expect-error 123
const selectedAnalogInputSlice = createSlice<SelectedAnalogInput | null>({
name: "selectedAnalogInput",
initialState,
reducers: {
setSelectedAnalogInput: (
state,
_state,
action: PayloadAction<SelectedAnalogInput>
) => {
return action.payload;
},
clearSelectedAnalogInput: () => {
return null;
},
) => action.payload,
resetSelectedAnalogInput: () => null,
},
});
export const { setSelectedAnalogInput, clearSelectedAnalogInput } =
export const { setSelectedAnalogInput, resetSelectedAnalogInput } =
selectedAnalogInputSlice.actions;
export default selectedAnalogInputSlice.reducer;

View File

@@ -4,16 +4,22 @@ export interface AnalogInput {
label: string;
unit?: string;
value: number;
name: string;
// Schwellenwerte (Statusflags)
// Statusflags
isUnderWarning?: boolean;
isUnderLimit?: boolean;
isOverWarning?: boolean;
isOverLimit?: boolean;
// Erweiterbar für spätere Charts
// Weitere optionale Felder
offset?: number;
factor?: number;
loggerInterval?: number;
weighting?: number;
// Zusätzliche Felder im Slice
uW?: boolean;
uG?: boolean;
oW?: boolean;
oG?: boolean;
}

6
types/digitalOutput.ts Normal file
View File

@@ -0,0 +1,6 @@
// /types/digitalOutput.ts
export interface DigitalOutput {
id: number;
label: string;
status: boolean;
}