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_EXPORT_STATIC=false
NEXT_PUBLIC_USE_CGI=false NEXT_PUBLIC_USE_CGI=false
# App-Versionsnummer # 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) 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_EXPORT_STATIC=true
NEXT_PUBLIC_USE_CGI=true NEXT_PUBLIC_USE_CGI=true
# App-Versionsnummer # App-Versionsnummer
NEXT_PUBLIC_APP_VERSION=1.6.482 NEXT_PUBLIC_APP_VERSION=1.6.483
NEXT_PUBLIC_CPL_MODE=production NEXT_PUBLIC_CPL_MODE=production

View File

@@ -1,6 +1,20 @@
{ {
"extends": [ "extends": [
"next",
"next/core-web-vitals", "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 #!/bin/sh
echo "🔄 Version wird automatisch erhöht (bumpVersion.ts)..." echo "🔄 Version wird automatisch erhöht (bumpVersion.ts)..."
npx husky add .husky/pre-commit "npm run check" npm run check
# 1. Version erhöhen # 1. Version erhöhen
npx ts-node scripts/bumpVersion.ts || exit 1 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 # 4. Dateien zum Commit hinzufügen
git add package.json package-lock.json CHANGELOG.md .env.development .env.production 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 ## [1.6.482] 2025-06-26
- feat: Tabellenkopf in Berichte-Seite fixiert und Scrollen verbessert - 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 { RootState } from "@/redux/store";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store"; import { AppDispatch } from "@/redux/store";
import decodeToken from "@/utils/decodeToken";
import { getSystemSettingsThunk } from "@/redux/thunks/getSystemSettingsThunk"; import { getSystemSettingsThunk } from "@/redux/thunks/getSystemSettingsThunk";
function Header() { function Header() {
@@ -16,7 +16,6 @@ function Header() {
const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false); const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false);
// Removed duplicate declaration of deviceName // Removed duplicate declaration of deviceName
const handleSettingsClick = () => setShowSettingsModal(true);
const handleCloseSettingsModal = () => setShowSettingsModal(false); const handleCloseSettingsModal = () => setShowSettingsModal(false);
const handleLogout = () => { const handleLogout = () => {
@@ -26,13 +25,6 @@ function Header() {
router.push("/offline.html"); // Weiterleitung 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(() => { useEffect(() => {
// Initialer Check beim Laden der Komponente // Initialer Check beim Laden der Komponente
const isAdmin = localStorage.getItem("isAdminLoggedIn") === "true"; const isAdmin = localStorage.getItem("isAdminLoggedIn") === "true";

View File

@@ -1,5 +1,5 @@
"use client"; // components/header/settingsModal/SettingsModal.tsx "use client"; // components/header/settingsModal/SettingsModal.tsx
import React, { useState, useEffect } from "react"; import React, { useState } from "react";
import ReactModal from "react-modal"; import ReactModal from "react-modal";
import "bootstrap-icons/font/bootstrap-icons.css"; import "bootstrap-icons/font/bootstrap-icons.css";
import { RootState } from "../../../redux/store"; import { RootState } from "../../../redux/store";
@@ -8,13 +8,7 @@ import handleClearDatabase from "./handlers/handleClearDatabase";
import handleReboot from "./handlers/handleReboot"; import handleReboot from "./handlers/handleReboot";
import handleSetDateTime from "./handlers/handleSetDateTime"; import handleSetDateTime from "./handlers/handleSetDateTime";
import handleSubmit from "./handlers/handleSubmit"; import handleSubmit from "./handlers/handleSubmit";
import bcrypt from "bcryptjs";
import CryptoJS from "crypto-js";
import { useAdminAuth } from "./hooks/useAdminAuth"; 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"); ReactModal.setAppElement("#__next");
@@ -27,13 +21,6 @@ function SettingModal({
}) { }) {
const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(showModal); 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( const deviceName_Redux = useSelector(
(state: RootState) => state.systemSettingsSlice.deviceName (state: RootState) => state.systemSettingsSlice.deviceName
); );
@@ -69,11 +56,11 @@ function SettingModal({
); );
const [name, setName] = useState(deviceName_Redux || ""); const [name, setName] = useState(deviceName_Redux || "");
const [mac1, setMac1] = useState(mac1_Redux || ""); const [mac1] = useState(mac1_Redux || "");
const [ip, setIp] = useState(ip_Redux || ""); const [ip, setIp] = useState(ip_Redux || "");
const [subnet, setSubnet] = useState(subnet_Redux || ""); const [subnet, setSubnet] = useState(subnet_Redux || "");
const [gateway, setGateway] = useState(gateway_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 [ntp1, setNtp1] = useState(ntp1_Redux || "");
const [ntp2, setNtp2] = useState(ntp2_Redux || ""); const [ntp2, setNtp2] = useState(ntp2_Redux || "");
const [ntp3, setNtp3] = useState(ntp3_Redux || ""); const [ntp3, setNtp3] = useState(ntp3_Redux || "");
@@ -82,7 +69,7 @@ function SettingModal({
typeof active_Redux === "boolean" ? active_Redux : active_Redux === "true" typeof active_Redux === "boolean" ? active_Redux : active_Redux === "true"
); );
const [originalValues, setOriginalValues] = useState({ const [originalValues] = useState({
name: name, name: name,
ip: ip, ip: ip,
subnet: subnet, subnet: subnet,
@@ -93,6 +80,8 @@ function SettingModal({
ntpTimezone: ntpTimezone, ntpTimezone: ntpTimezone,
active: active, active: active,
}); });
// const [showLoginForm, setShowLoginForm] = useState(false);
const currentValues = { const currentValues = {
name, name,
ip, ip,
@@ -266,9 +255,7 @@ function SettingModal({
Neustart CPL Neustart CPL
</button> </button>
<button <button
onClick={() => onClick={() => (isAdminLoggedIn ? logoutAdmin() : null)}
isAdminLoggedIn ? logoutAdmin() : setShowLoginForm(true)
}
className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full md:w-auto" 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"} {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 = { type Props = {
className?: string; className?: string;
onClick?: () => void; onClick?: () => void;
}; };
export default function CogIcon({ className, onClick }: Props) { const CogIcon: React.FC<Props> = ({ className, onClick }) => (
return ( <Image
<img
src="/icons/mdi--cog-outline.svg" src="/icons/mdi--cog-outline.svg"
alt="Einstellungen" alt="Einstellungen"
className={className} className={className}
onClick={onClick} onClick={onClick}
width={24}
height={24}
/> />
); );
}
export default CogIcon;

View File

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

View File

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

View File

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

View File

@@ -9,7 +9,12 @@ import inputIcon from "@iconify/icons-mdi/input";
import loginIcon from "@iconify/icons-mdi/login"; import loginIcon from "@iconify/icons-mdi/login";
type Props = { type Props = {
openInputModal: (input: any) => void; openInputModal: (input: {
id: number;
eingangOffline: boolean;
status: boolean;
label: string;
}) => void;
inputRange: { start: number; end: number }; 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 outputIcon from "@iconify/icons-mdi/output";
import switchIcon from "@iconify/icons-ion/switch"; import switchIcon from "@iconify/icons-ion/switch";
import { setDigitalOutputs } from "@/redux/slices/digitalOutputsSlice"; import { setDigitalOutputs } from "@/redux/slices/digitalOutputsSlice";
import type { DigitalOutput } from "@/types/digitalOutput";
interface DigitalOutputsWidgetProps { export interface DigitalOutputsWidgetProps {
openOutputModal: (output: any) => void; openOutputModal: (output: DigitalOutput) => void;
} }
export default function DigitalOutputsWidget({ export default function DigitalOutputsWidget({

View File

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

View File

@@ -3,13 +3,12 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/redux/store"; import { RootState } from "@/redux/store";
import switchIcon from "@iconify/icons-ion/switch";
import { updateInvert, updateLabel } from "@/redux/slices/digitalInputsSlice"; import { updateInvert, updateLabel } from "@/redux/slices/digitalInputsSlice";
type InputModalProps = { type InputModalProps = {
selectedInput: { selectedInput: {
id: number; id: number;
[key: string]: any; [key: string]: unknown;
} | null; } | null;
closeInputModal: () => void; closeInputModal: () => void;
isOpen: boolean; isOpen: boolean;
@@ -51,8 +50,24 @@ export default function InputModal({
} }
}, [reduxInput, isInitialLoad]); }, [reduxInput, isInitialLoad]);
useEffect(() => {
if (isOpen && selectedInput) {
setIsInitialLoad(true);
}
}, [isOpen, selectedInput]);
useEffect(() => {
if (isOpen && selectedInput) {
setIsInitialLoad(true);
}
}, [isOpen, selectedInput]);
if (!isOpen || !selectedInput || !reduxInput) return null; if (!isOpen || !selectedInput || !reduxInput) return null;
const handleClose = () => {
closeInputModal();
};
const sendCgiUpdate = async (param: string) => { const sendCgiUpdate = async (param: string) => {
const url = `/CPL?/eingaenge.html&${param}`; const url = `/CPL?/eingaenge.html&${param}`;
//console.log("📡 CGI senden:", url); //console.log("📡 CGI senden:", url);
@@ -103,7 +118,15 @@ export default function InputModal({
alert("✅ Daten erfolgreich an die CPL-Hardware gesendet!"); alert("✅ Daten erfolgreich an die CPL-Hardware gesendet!");
} else { } else {
// ENTWICKLUNGSUMGEBUNG (lokale API) // 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) { if (label !== reduxInput.label) {
updates.label = label; updates.label = label;
dispatch(updateLabel({ id, label })); dispatch(updateLabel({ id, label }));
@@ -148,21 +171,15 @@ export default function InputModal({
setIsInitialLoad(true); setIsInitialLoad(true);
closeInputModal(); closeInputModal();
} catch (err: any) { } catch (err: unknown) {
if (err instanceof Error) {
alert("❌ Fehler beim Speichern: " + err.message); 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 ( 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="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"> <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 "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 ReactModal from "react-modal";
import LoopChartActionBar from "./LoopMeasurementChart/LoopChartActionBar"; import LoopChartActionBar from "./LoopMeasurementChart/LoopChartActionBar";
import TDRChartActionBar from "./TDRChart/TDRChartActionBar";
import LoopMeasurementChart from "./LoopMeasurementChart/LoopMeasurementChart"; import LoopMeasurementChart from "./LoopMeasurementChart/LoopMeasurementChart";
import TDRChart from "./TDRChart/TDRChart"; import TDRChart from "./TDRChart/TDRChart";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "../../../../../redux/store"; import { AppDispatch } from "@/redux/store";
import { RootState } from "../../../../../redux/store"; import { RootState } from "@/redux/store";
import { import {
setChartOpen, setChartOpen,
setFullScreen, setFullScreen,
} from "../../../../../redux/slices/kabelueberwachungChartSlice"; } from "@/redux/slices/kabelueberwachungChartSlice";
import {
setSelectedSlot, import { resetBrushRange } from "@/redux/slices/brushSlice";
setSelectedChartType,
} from "../../../../../redux/slices/tdrChartSlice";
import { resetBrushRange } from "../../../../../redux/slices/brushSlice";
import { fetchTDMDataBySlotThunk } from "../../../../../redux/thunks/getTDMListBySlotThunk";
import { useLoopChartLoader } from "./LoopMeasurementChart/LoopChartActionBar"; import { useLoopChartLoader } from "./LoopMeasurementChart/LoopChartActionBar";
import { import {
@@ -26,7 +21,7 @@ import {
setBisDatum, setBisDatum,
setSelectedMode, setSelectedMode,
setSelectedSlotType, setSelectedSlotType,
} from "../../../../../redux/slices/kabelueberwachungChartSlice"; } from "@/redux/slices/kabelueberwachungChartSlice";
interface ChartSwitcherProps { interface ChartSwitcherProps {
isOpen: boolean; isOpen: boolean;
@@ -34,11 +29,7 @@ interface ChartSwitcherProps {
slotIndex: number; slotIndex: number;
} }
const ChartSwitcher: React.FC<ChartSwitcherProps> = ({ const ChartSwitcher: React.FC<ChartSwitcherProps> = ({ isOpen, onClose }) => {
isOpen,
onClose,
slotIndex,
}) => {
const dispatch = useDispatch<AppDispatch>(); const dispatch = useDispatch<AppDispatch>();
const chartTitle = useSelector( const chartTitle = useSelector(
(state: RootState) => state.loopChartType.chartTitle (state: RootState) => state.loopChartType.chartTitle
@@ -82,24 +73,20 @@ const ChartSwitcher: React.FC<ChartSwitcherProps> = ({
}; };
// **Slot und Messkurve setzen** // **Slot und Messkurve setzen**
const setChartType = (chartType: "TDR" | "Schleife") => { // const setChartType = (chartType: "TDR" | "Schleife") => {
dispatch(setSelectedSlot(slotIndex)); // dispatch(setSelectedSlot(slotIndex));
dispatch(setSelectedChartType(chartType)); // dispatch(setSelectedChartType(chartType));
}; // };
//-------------------------------------
const { loadLoopChartData } = useLoopChartLoader(); // useLoopChartLoader hook
useEffect(() => { const loadLoopChartData = useLoopChartLoader();
if (isOpen && activeMode === "Schleife") {
loadLoopChartData(); // Slot number from Redux
}
}, [isOpen, activeMode]);
//-------------------------------------
const slotNumber = useSelector( const slotNumber = useSelector(
(state: RootState) => state.kabelueberwachungChartSlice.slotNumber (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(() => { useEffect(() => {
if (isOpen && activeMode === "Schleife" && slotNumber !== null) { if (isOpen && activeMode === "Schleife" && slotNumber !== null) {
const today = new Date(); const today = new Date();
@@ -113,12 +100,11 @@ const ChartSwitcher: React.FC<ChartSwitcherProps> = ({
// Warten, bis Redux gesetzt ist → dann Daten laden // Warten, bis Redux gesetzt ist → dann Daten laden
setTimeout(() => { setTimeout(() => {
loadLoopChartData(); loadLoopChartData.loadLoopChartData();
}, 10); // kleiner Delay, damit Redux-State sicher aktualisiert ist }, 10); // kleiner Delay, damit Redux-State sicher aktualisiert ist
} }
}, [isOpen, activeMode, slotNumber]); }, [isOpen, activeMode, slotNumber, dispatch, loadLoopChartData]);
//-----------------------------------------
return ( return (
<ReactModal <ReactModal
isOpen={isOpen} isOpen={isOpen}

View File

@@ -4,7 +4,14 @@ import React from "react";
interface CustomTooltipProps { interface CustomTooltipProps {
active?: boolean; 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; label?: string;
unit?: string; unit?: string;
} }

View File

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

View File

@@ -3,24 +3,22 @@
import React from "react"; import React from "react";
import DateRangePicker from "./DateRangePicker"; import DateRangePicker from "./DateRangePicker";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store"; import { RootState } from "@/redux/store";
import { import {
setVonDatum,
setBisDatum,
setLoopMeasurementCurveChartData, setLoopMeasurementCurveChartData,
setSelectedMode, setSelectedMode,
setSelectedSlotType, setSelectedSlotType,
setChartOpen, setChartOpen,
setFullScreen,
setLoading, setLoading,
} from "../../../../../../redux/slices/kabelueberwachungChartSlice"; } from "@/redux/slices/kabelueberwachungChartSlice";
import { setBrushRange } from "../../../../../../redux/slices/brushSlice"; import { setBrushRange } from "@/redux/slices/brushSlice";
import { setChartTitle } from "../../../../../../redux/slices/loopChartTypeSlice"; import { setChartTitle } from "@/redux/slices/loopChartTypeSlice";
//-----------------------------------------------------------------------------------useLoopChartLoader //-----------------------------------------------------------------------------------useLoopChartLoader
export const useLoopChartLoader = () => { export const useLoopChartLoader = () => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { vonDatum, bisDatum, selectedMode, selectedSlotType, slotNumber } = const { vonDatum, bisDatum, selectedMode, selectedSlotType, slotNumber } =
useSelector((state: RootState) => state.kabelueberwachungChartSlice); useSelector((state: RootState) => state.kabelueberwachungChartSlice);
const hasShownNoDataAlert = React.useRef(false);
const formatDate = (dateString: string) => { const formatDate = (dateString: string) => {
const [year, month, day] = dateString.split("-"); const [year, month, day] = dateString.split("-");
@@ -77,7 +75,10 @@ export const useLoopChartLoader = () => {
} else { } else {
dispatch(setLoopMeasurementCurveChartData([])); dispatch(setLoopMeasurementCurveChartData([]));
dispatch(setChartOpen(false)); 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) { } catch (err) {
console.error("❌ Fehler beim Laden:", err); console.error("❌ Fehler beim Laden:", err);
@@ -99,9 +100,9 @@ const LoopChartActionBar: React.FC = () => {
bisDatum, bisDatum,
selectedMode, selectedMode,
selectedSlotType, selectedSlotType,
isChartOpen,
slotNumber, slotNumber,
loopMeasurementCurveChartData,
isLoading, isLoading,
} = useSelector((state: RootState) => state.kabelueberwachungChartSlice); } = 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 React, { useEffect, useRef } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store"; import { RootState } from "@/redux/store";
import { import {
Chart as ChartJS, Chart as ChartJS,
LineElement, LineElement,
@@ -32,8 +32,16 @@ ChartJS.register(
import { getColor } from "../../../../../../utils/colors"; import { getColor } from "../../../../../../utils/colors";
import { PulseLoader } from "react-spinners"; import { PulseLoader } from "react-spinners";
const usePreviousData = (data: any[]) => { type LoopMeasurementEntry = {
const ref = useRef<any[]>([]); t: string;
i: number;
m: number;
g: number;
a: number;
};
const usePreviousData = (data: LoopMeasurementEntry[]) => {
const ref = useRef<LoopMeasurementEntry[]>([]);
useEffect(() => { useEffect(() => {
ref.current = data; ref.current = data;
}, [data]); }, [data]);
@@ -57,7 +65,10 @@ const LoopMeasurementChart = () => {
const previousData = usePreviousData(loopMeasurementCurveChartData); const previousData = usePreviousData(loopMeasurementCurveChartData);
// Vergleichsfunktion // Vergleichsfunktion
const isEqual = (a: any[], b: any[]): boolean => { const isEqual = (
a: LoopMeasurementEntry[],
b: LoopMeasurementEntry[]
): boolean => {
if (a.length !== b.length) return false; if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) { for (let i = 0; i < a.length; i++) {
if ( if (
@@ -196,6 +207,7 @@ const LoopMeasurementChart = () => {
options, options,
}); });
}); });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [loopMeasurementCurveChartData, selectedMode, vonDatum, bisDatum]); }, [loopMeasurementCurveChartData, selectedMode, vonDatum, bisDatum]);
return ( return (

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -32,13 +32,13 @@ export interface HandleSaveParams {
speicherintervall: number[]; speicherintervall: number[];
}; };
slot: number; slot: number;
dispatch: any; dispatch: import("redux").Dispatch;
onModulNameChange: (id: string) => void; onModulNameChange: (id: string) => void;
onClose: () => 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 aNum = Number(a);
const bNum = Number(b); const bNum = Number(b);
if (!isNaN(aNum) && !isNaN(bNum)) { if (!isNaN(aNum) && !isNaN(bNum)) {
@@ -62,7 +62,7 @@ const handleSave = async ({
onModulNameChange, onModulNameChange,
onClose, onClose,
}: HandleSaveParams): Promise<void> => { }: HandleSaveParams): Promise<void> => {
const changesForFile: Record<string, any> = {}; const changesForFile: Record<string, string | number> = {};
if (isDifferent(ids[slot], originalValues.kueID[slot])) { if (isDifferent(ids[slot], originalValues.kueID[slot])) {
changesForFile.KID = ids[slot]; changesForFile.KID = ids[slot];

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,11 +1,17 @@
"use client"; "use client";
type TdrData = {
daempfung: string;
geschwindigkeit: string;
trigger: string;
};
declare global { declare global {
interface Window { 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 { useSelector } from "react-redux";
import { RootState } from "../../../../../redux/store"; import { RootState } from "../../../../../redux/store";

View File

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

View File

@@ -1,30 +1,31 @@
"use client"; "use client";
import React from "react"; import React from "react";
import { useSelector, useDispatch } from "react-redux"; import { useSelector } from "react-redux";
import { RootState } from "../../../redux/store"; import { RootState } from "../../../redux/store";
import handleNtpSubmit from "./handlers/handleNtpSubmit"; import handleNtpSubmit from "./handlers/handleNtpSubmit";
const NTPSettings: React.FC = () => { const NTPSettings: React.FC = () => {
const dispatch = useDispatch();
const systemSettings = useSelector( const systemSettings = useSelector(
(state: RootState) => state.systemSettingsSlice (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 // Wenn Daten noch nicht geladen sind, Ladeanzeige anzeigen
if (!systemSettings || systemSettings.ntp1 === undefined) { if (!systemSettings || systemSettings.ntp1 === undefined) {
return <p className="text-xs text-gray-500">Lade NTP-Daten...</p>; 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 ( return (
<div className="p-6 md:p-3 bg-gray-100 max-w-5xl mr-auto"> <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> <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 "use client"; // /components/main/settingsPageComponents/OPCUAInterfaceSettings.tsx
import React, { useState } from "react"; import React, { useState } from "react";
import Image from "next/image";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../redux/store"; import { RootState } from "../../../redux/store";
import { import { toggleOpcUaServer } from "../../../redux/slices/opcuaSettingsSlice";
setOpcUaEncryption,
toggleOpcUaServer,
setOpcUaNodesetName,
addOpcUaUser,
removeOpcUaUser,
} from "../../../redux/slices/opcuaSettingsSlice";
export default function OPCUAInterfaceSettings() { export default function OPCUAInterfaceSettings() {
const dispatch = useDispatch(); const dispatch = useDispatch();
@@ -17,29 +12,28 @@ export default function OPCUAInterfaceSettings() {
); );
// Lokale Zustände für das neue Benutzerformular // Lokale Zustände für das neue Benutzerformular
const [newUsername, setNewUsername] = useState("");
const [newPassword, setNewPassword] = useState("");
const [nodesetName, setNodesetName] = useState( const [nodesetName, setNodesetName] = useState(
opcuaSettings.opcUaNodesetName opcuaSettings.opcUaNodesetName
); );
const handleAddUser = () => {
if (newUsername.trim() && newPassword.trim()) {
dispatch(addOpcUaUser({ username: newUsername, password: newPassword }));
setNewUsername("");
setNewPassword("");
}
};
const handleNodesetUpdate = () => {
dispatch(setOpcUaNodesetName(nodesetName));
};
return ( return (
<div className="p-6 md:p-3 bg-gray-100 max-w-5xl mr-auto "> <div className="p-6 md:p-3 bg-gray-100 max-w-5xl mr-auto ">
<div className="flex justify-between items-center mb-3"> <div className="flex justify-between items-center mb-3">
<h2 className="text-base font-semibold">OPCUA Server Einstellungen</h2> <Image
<img src="/images/OPCUA.jpg" alt="OPCUA Logo" className="h-12 w-auto" /> 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> </div>
{/* ✅ Server Aktivierung */} {/* ✅ Server Aktivierung */}

View File

@@ -2,14 +2,15 @@
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import { generateToken } from "../utils/cryptoUtils"; import { generateToken } from "../utils/cryptoUtils";
import USERS from "../config/users"; 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 = ( const handleAdminLogin = (
username: string, username: string,
password: string, password: string,
onSuccess: () => void, onSuccess: () => void,
onError: (errorMsg: string) => void, onError: (message: string) => void,
dispatch: any // ✅ neu dispatch: AppDispatch // Use the correct dispatch type
) => { ) => {
const user = USERS.Admin; const user = USERS.Admin;
bcrypt.compare(password, user.password, (err, isMatch) => { bcrypt.compare(password, user.password, (err, isMatch) => {

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

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

View File

@@ -1,6 +1,6 @@
{ {
"win_da_state": [ "win_da_state": [
1, 0,
0, 0,
0, 0,
1 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", "name": "cpl-v4",
"version": "1.6.482", "version": "1.6.483",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "cpl-v4", "name": "cpl-v4",
"version": "1.6.482", "version": "1.6.483",
"dependencies": { "dependencies": {
"@fontsource/roboto": "^5.1.0", "@fontsource/roboto": "^5.1.0",
"@iconify-icons/ri": "^1.2.10", "@iconify-icons/ri": "^1.2.10",

View File

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

View File

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

View File

@@ -1,14 +1,23 @@
"use client"; ///pages/analogeEingaenge.tsx "use client"; ///pages/analogeEingaenge.tsx
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import AnalogInputsTable from "../components/main/analogInputs/AnalogInputsTable"; import AnalogInputsTable from "@/components/main/analogInputs/AnalogInputsTable";
import AnalogInputsChart from "../components/main/analogInputs/AnalogInputsChart"; import AnalogInputsChart from "@/components/main/analogInputs/AnalogInputsChart";
import AnalogInputsSettingsModal from "../components/main/analogInputs/AnalogInputsSettingsModal"; import AnalogInputsSettingsModal from "@/components/main/analogInputs/AnalogInputsSettingsModal";
import { getAnalogInputsThunk } from "../redux/thunks/getAnalogInputsThunk"; import { getAnalogInputsThunk } from "@/redux/thunks/getAnalogInputsThunk";
import { useAppDispatch } from "../redux/store"; import { useAppDispatch } from "@/redux/store";
export interface AnalogInput2 {
id: number;
label?: string;
offset?: number | string;
factor?: number | string;
loggerInterval: string;
unit?: string;
}
function AnalogInputs() { function AnalogInputs() {
const [selectedId, setSelectedId] = useState<number | null>(null); 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 [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
@@ -26,18 +35,20 @@ function AnalogInputs() {
<div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)]"> <div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)]">
<div className="container mx-auto"> <div className="container mx-auto">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-white rounded-lg p-4 "> <div className="bg-white rounded-lg p-4">
<h2 className="text-xl font-semibold mb-4 text-gray-700"> <h2 className="text-xl font-semibold mb-4 text-gray-700">
Messwerteingänge Messwerteingänge
</h2> </h2>
<AnalogInputsTable <AnalogInputsTable
setSelectedId={setSelectedId} setSelectedId={setSelectedId}
setSelectedInput={setSelectedInput} setSelectedInput={(input) =>
setSelectedInput(input as unknown as AnalogInput2)
}
setIsSettingsModalOpen={setIsSettingsModalOpen} setIsSettingsModalOpen={setIsSettingsModalOpen}
/> />
</div> </div>
<div className="bg-white shadow-lg rounded-lg p-4 border border-gray-200 "> <div className="bg-white shadow-lg rounded-lg p-4 border border-gray-200">
<h2 className="text-xl font-semibold mb-4 text-gray-700"> <h2 className="text-xl font-semibold mb-4 text-gray-700">
Messkurve Messwerteingang {selectedId ?? ""} Messkurve Messwerteingang {selectedId ?? ""}
</h2> </h2>
@@ -46,11 +57,13 @@ function AnalogInputs() {
</div> </div>
</div> </div>
{selectedInput !== null && (
<AnalogInputsSettingsModal <AnalogInputsSettingsModal
selectedInput={selectedInput} selectedInput={selectedInput}
isOpen={isSettingsModalOpen} isOpen={isSettingsModalOpen}
onClose={() => setIsSettingsModalOpen(false)} onClose={() => setIsSettingsModalOpen(false)}
/> />
)}
</div> </div>
); );
} }

View File

@@ -9,7 +9,7 @@ export default async function handler(
res: NextApiResponse res: NextApiResponse
) { ) {
try { try {
const result: Record<number, any[]> = {}; const result: Record<number, unknown[]> = {};
for (let i = 1; i <= 8; i++) { for (let i = 1; i <= 8; i++) {
const filePath = path.join( const filePath = path.join(
@@ -22,10 +22,11 @@ export default async function handler(
try { try {
const fileContent = await fs.readFile(filePath, "utf-8"); const fileContent = await fs.readFile(filePath, "utf-8");
result[99 + i] = JSON.parse(fileContent); // z.B. 100 für AE1, 101 für AE2 result[99 + i] = JSON.parse(fileContent); // z. B. 100 für AE1, 101 für AE2
} catch (err) { } catch (error) {
console.warn( 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] = []; 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 { NextApiRequest, NextApiResponse } from "next";
import path from "path"; import path from "path";
@@ -12,7 +12,7 @@ export default async function handler(
const mode = process.env.NEXT_PUBLIC_CPL_MODE ?? "json"; const mode = process.env.NEXT_PUBLIC_CPL_MODE ?? "json";
if (mode === "json") { if (mode === "json") {
// Lese JSON-Datei z.B. digitalOutputsMockData.json // Lese JSON-Datei z.B. digitalOutputsMockData.json
const filePath = path.join( const filePath = path.join(
process.cwd(), process.cwd(),
"mocks/api/SERVICE/digitalOutputsMockData.json" "mocks/api/SERVICE/digitalOutputsMockData.json"

View File

@@ -20,6 +20,10 @@ export default async function handler(
const data = await fs.readFile(filePath, "utf-8"); const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data); res.status(200).send(data);
} catch (error) { } 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.setHeader("Content-Type", "text/javascript"); // wichtig!
res.status(200).send(data); res.status(200).send(data);
} catch (error) { } 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 { function parseDate(str: string): Date {
return new Date(str.replace(" ", "T")); 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( export default async function handler(
req: NextApiRequest, req: NextApiRequest,
@@ -38,8 +45,8 @@ export default async function handler(
} }
if (fromDate && toDate) { if (fromDate && toDate) {
const filtered = data.filter((msg: any) => { const filtered = data.filter((msg: Message) => {
const messageDate = parseDate(msg.t); const messageDate = parseDate(msg.timestamp);
return messageDate >= fromDate! && messageDate <= toDate!; return messageDate >= fromDate! && messageDate <= toDate!;
}); });

View File

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

View File

@@ -3,10 +3,24 @@ import { NextApiRequest, NextApiResponse } from "next";
import path from "path"; import path from "path";
import fs from "fs/promises"; 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 // Hilfsfunktion: JSON-Datei laden
async function loadJsonData(filePath: string) { async function loadJsonData(filePath: string): Promise<ChartDataEntry[]> {
const data = await fs.readFile(filePath, "utf8"); 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( export default async function handler(
@@ -32,20 +46,23 @@ export default async function handler(
try { try {
const jsonData = await loadJsonData(jsonFilePath); const jsonData = await loadJsonData(jsonFilePath);
// Filtern nach Datum, wenn angegeben
let filteredData = jsonData; let filteredData = jsonData;
if (vonDatum && bisDatum) { if (vonDatum && bisDatum) {
const von = new Date(`${vonDatum}T00:00:00`); const von = new Date(`${vonDatum}T00:00:00`);
const bis = new Date(`${bisDatum}T23:59:59`); const bis = new Date(`${bisDatum}T23:59:59`);
filteredData = jsonData.filter((item: any) => { filteredData = jsonData.filter((item) => {
const timestamp = new Date(item.t); const dateString = item.timestamp ?? item.zeit ?? item.time;
return timestamp >= von && timestamp <= bis; 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) { } 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"); const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data); res.status(200).send(data);
} catch (error) { } catch (error) {
console.error("Error processing systemAPIHandler:", error);
res.status(404).json({ error: "File not found" }); 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"); const data = await fs.readFile(filePath, "utf-8");
res.status(200).send(data); res.status(200).send(data);
} catch (error) { } catch (error) {
console.error("Error processing systemVoltTempAPIHandler:", error);
res.status(404).json({ error: "File not found" }); 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"); const data = await fs.readFile(filePath, "utf-8");
res.status(200).json(JSON.parse(data)); res.status(200).json(JSON.parse(data));
} catch (error) { } catch (error) {
console.error("Error processing tdmDataAPIHandler:", error);
res.status(404).json({ error: "File not found" }); 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"); const data = await fs.readFile(filePath, "utf-8");
res.status(200).json(JSON.parse(data)); res.status(200).json(JSON.parse(data));
} catch (error) { } catch (error) {
console.error("Error processing tdrDataAPIHandler:", error);
res.status(404).json({ error: "File not found" }); 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"); const fileContent = await fs.readFile(filePath, "utf-8");
res.status(200).json(JSON.parse(fileContent)); res.status(200).json(JSON.parse(fileContent));
} catch (error) { } catch (error) {
console.error("Error processing tdrReferenceCurveAPIHandler:", error);
res.status(404).json({ error: "File not found" }); res.status(404).json({ error: "File not found" });
} }
} }

View File

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

View File

@@ -6,7 +6,7 @@ export default async function handler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ) {
let { key, value, slot } = req.query; const { key, value, slot } = req.query;
if ( if (
typeof key !== "string" || 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"); await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
res.status(200).json({ success: true }); res.status(200).json({ success: true });
} catch (error) { } catch (error) {
console.error("Error processing updateTdrReferenceCurveAPIHandler:", error);
res.status(500).json({ error: "Failed to save file" }); 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] || ""; const arrayRaw = match[0].match(/\[(.*)\]/s)?.[1] || "";
let values = arrayRaw const values = arrayRaw
.split(",") .split(",")
.map((v) => v.trim()) .map((v) => v.trim())
.map((v) => (v === "" ? "0" : v)) .map((v) => (v === "" ? "0" : v))
@@ -45,10 +45,7 @@ export default async function handler(
} }
// Bereinige kaputte Endzeilen wie ")" // Bereinige kaputte Endzeilen wie ")"
fileContent = fileContent.replace( fileContent = fileContent.replace(/^\s*[)(a-zA-Z0-9/:. ]{2,40}\s*$/gm, "");
/^\s*[\)\(a-zA-Z0-9\/\:\. ]{2,40}\s*$/gm,
""
);
await fs.writeFile(filePath, fileContent, "utf-8"); await fs.writeFile(filePath, fileContent, "utf-8");

View File

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

View File

@@ -1,43 +1,40 @@
"use client"; "use client";
// /pages/digitalInputs.tsx // /pages/digitalInputs.tsx
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../redux/store"; 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 { 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 EinAusgaenge: React.FC = () => {
const dispatch = useDispatch<AppDispatch>(); const dispatch = useDispatch<AppDispatch>();
const digitalInputs = useSelector( interface DigitalInput {
(state: RootState) => state.digitalInputsSlice.inputs id: number;
); eingangOffline: boolean;
const digitalOutputs = useSelector( status: boolean;
(state: RootState) => state.digitalOutputsSlice.outputs 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 [isInputModalOpen, setIsInputModalOpen] = useState(false);
const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);
useEffect(() => { useEffect(() => {
dispatch(getDigitalInputsThunk()); dispatch(getDigitalInputsThunk());
dispatch(getDigitalOutputsThunk());
const interval = setInterval(() => { const interval = setInterval(() => {
dispatch(getDigitalInputsThunk()); dispatch(getDigitalInputsThunk());
dispatch(getDigitalOutputsThunk());
}, 10000); }, 10000);
return () => clearInterval(interval); return () => clearInterval(interval);
}, [dispatch]); }, [dispatch]);
const openInputModal = (input: any) => { const openInputModal = (input: DigitalInput) => {
setSelectedInput(input); setSelectedInput(input);
setIsInputModalOpen(true); setIsInputModalOpen(true);
}; };
@@ -47,16 +44,6 @@ const EinAusgaenge: React.FC = () => {
setIsInputModalOpen(false); setIsInputModalOpen(false);
}; };
const openOutputModal = (output: any) => {
setSelectedOutput(output);
setIsOutputModalOpen(true);
};
const closeOutputModal = () => {
setSelectedOutput(null);
setIsOutputModalOpen(false);
};
return ( 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"> <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> <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 React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch } from "react-redux";
import { AppDispatch, RootState } from "@/redux/store"; import { AppDispatch } from "@/redux/store";
import DigitalOutputsModal from "../components/main/einausgaenge/modals/DigitalOutputsModal"; import DigitalOutputsModal from "../components/main/einausgaenge/modals/DigitalOutputsModal";
import DigitalOutputs from "../components/main/einausgaenge/DigitalOutputsWidget";
import { getDigitalInputsThunk } from "@/redux/thunks/getDigitalInputsThunk"; import { getDigitalInputsThunk } from "@/redux/thunks/getDigitalInputsThunk";
import { getDigitalOutputsThunk } from "@/redux/thunks/getDigitalOutputsThunk"; import { getDigitalOutputsThunk } from "@/redux/thunks/getDigitalOutputsThunk";
import DigitalOutputs from "../components/main/einausgaenge/DigitalOutputsWidget"; import type { DigitalOutput } from "@/types/digitalOutput";
const EinAusgaenge: React.FC = () => { const EinAusgaenge: React.FC = () => {
const dispatch = useDispatch<AppDispatch>(); const dispatch = useDispatch<AppDispatch>();
const [selectedOutput, setSelectedOutput] = useState<DigitalOutput | null>(
const digitalOutputs = useSelector( null
(state: RootState) => state.digitalOutputsSlice.outputs
); );
const [selectedOutput, setSelectedOutput] = useState(null);
const [isOutputModalOpen, setIsOutputModalOpen] = useState(false); const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);
useEffect(() => { useEffect(() => {
@@ -31,7 +30,7 @@ const EinAusgaenge: React.FC = () => {
return () => clearInterval(interval); return () => clearInterval(interval);
}, [dispatch]); }, [dispatch]);
const openOutputModal = (output: any) => { const openOutputModal = (output: DigitalOutput) => {
setSelectedOutput(output); setSelectedOutput(output);
setIsOutputModalOpen(true); setIsOutputModalOpen(true);
}; };
@@ -45,16 +44,17 @@ const EinAusgaenge: React.FC = () => {
<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"> <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">Schaltausgänge</h1> <h1 className="text-base font-semibold mb-2">Schaltausgänge</h1>
<div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start "> <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start">
<DigitalOutputs openOutputModal={openOutputModal} /> <DigitalOutputs openOutputModal={openOutputModal} />
</div> </div>
{/* ✅ Modal aktiv einbinden */} {selectedOutput && (
<DigitalOutputsModal <DigitalOutputsModal
selectedOutput={selectedOutput} selectedOutput={selectedOutput}
isOpen={isOutputModalOpen} isOpen={isOutputModalOpen}
closeOutputModal={closeOutputModal} closeOutputModal={closeOutputModal}
/> />
)}
</div> </div>
); );
}; };

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,16 +4,22 @@ export interface AnalogInput {
label: string; label: string;
unit?: string; unit?: string;
value: number; value: number;
name: string;
// Schwellenwerte (Statusflags) // Statusflags
isUnderWarning?: boolean; isUnderWarning?: boolean;
isUnderLimit?: boolean; isUnderLimit?: boolean;
isOverWarning?: boolean; isOverWarning?: boolean;
isOverLimit?: boolean; isOverLimit?: boolean;
// Erweiterbar für spätere Charts // Weitere optionale Felder
offset?: number; offset?: number;
factor?: number; factor?: number;
loggerInterval?: number;
weighting?: 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;
}