Fixed mail bug with static variable, fixed token encoding

This commit is contained in:
Noe 2023-10-26 16:38:37 +02:00
parent 76099131c2
commit 0a91445ddd
50 changed files with 1964 additions and 924 deletions

View File

@ -456,9 +456,9 @@ public class Controller : ControllerBase
}
[HttpPost(nameof(ResetPasswordRequest))]
public async Task<ActionResult<IEnumerable<Object>>> ResetPasswordRequest(String email)
public async Task<ActionResult<IEnumerable<Object>>> ResetPasswordRequest(String username)
{
var user = Db.GetUserByEmail(email);
var user = Db.GetUserByEmail(username);
if (user is null)
return Unauthorized();
@ -482,7 +482,7 @@ public class Controller : ControllerBase
Db.DeleteUserPassword(user);
return Redirect($"https://monitor.innov.energy/?username={user.Email}&reset=true");
return Redirect($"https://monnitor.innov.energy/?username={user.Email}&reset=true"); // TODO: move to settings file
}
}

View File

@ -1,4 +1,5 @@
using System.Security.Cryptography;
using System.Web;
using InnovEnergy.App.Backend.Database;
using InnovEnergy.Lib.Mailer;
using InnovEnergy.Lib.Utils;
@ -218,11 +219,12 @@ public static class UserMethods
public static Task SendPasswordResetEmail(this User user, String token)
{
const String subject = "Reset the password of your InnovEnergy-Account";
const String resetLink = "https://monitor.innov.energy/api/ResetPassword"; // TODO: move to settings file
const String resetLink = "https://monnitor.innov.energy/api/ResetPassword"; // TODO: move to settings file
var encodedToken = HttpUtility.UrlEncode(token);
var body = $"Dear {user.Name}\n" +
$"To reset your password " +
$"please open this link:{resetLink}?token={token}";
$"please open this link:{resetLink}?token={encodedToken}";
return user.SendEmail(subject, body);
}

View File

@ -7,7 +7,7 @@
"dotnetRunMessages": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7087",
"applicationUrl": "http://localhost:7087",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"HOME":"~/backend"

View File

@ -21,7 +21,7 @@
"chart.js": "^4.4.0",
"clsx": "1.1.1",
"cytoscape": "^3.26.0",
"date-fns": "2.28.0",
"date-fns": "^2.28.0",
"history": "5.3.0",
"linq-to-typescript": "^11.0.0",
"nprogress": "0.2.0",
@ -38,9 +38,11 @@
"react-icons": "^4.11.0",
"react-icons-converter": "^1.1.4",
"react-intl": "^6.4.4",
"react-redux": "^8.1.3",
"react-router": "6.3.0",
"react-router-dom": "6.3.0",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"rxjs": "^7.8.1",
"simplytyped": "^3.3.0",
"stylis": "4.1.1",
@ -4662,6 +4664,11 @@
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.2.tgz",
"integrity": "sha512-F5DIZ36YVLE+PN+Zwws4kJogq47hNgX3Nx6WyDJ3kcplxyke3XIzB8uK5n/Lpm1HBsbGzd6nmGehL8cPekP+Tg=="
},
"node_modules/@types/use-sync-external-store": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
},
"node_modules/@types/ws": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz",
@ -15155,6 +15162,49 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
},
"node_modules/react-redux": {
"version": "8.1.3",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-8.1.3.tgz",
"integrity": "sha512-n0ZrutD7DaX/j9VscF+uTALI3oUPa/pO4Z3soOBIjuRn/FzVu6aehhysxZCLi6y7duMf52WNZGMl7CtuK5EnRw==",
"dependencies": {
"@babel/runtime": "^7.12.1",
"@types/hoist-non-react-statics": "^3.3.1",
"@types/use-sync-external-store": "^0.0.3",
"hoist-non-react-statics": "^3.3.2",
"react-is": "^18.0.0",
"use-sync-external-store": "^1.0.0"
},
"peerDependencies": {
"@types/react": "^16.8 || ^17.0 || ^18.0",
"@types/react-dom": "^16.8 || ^17.0 || ^18.0",
"react": "^16.8 || ^17.0 || ^18.0",
"react-dom": "^16.8 || ^17.0 || ^18.0",
"react-native": ">=0.59",
"redux": "^4 || ^5.0.0-beta.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
},
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
},
"redux": {
"optional": true
}
}
},
"node_modules/react-redux/node_modules/react-is": {
"version": "18.2.0",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
"integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w=="
},
"node_modules/react-refresh": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
@ -15334,6 +15384,14 @@
"node": "*"
}
},
"node_modules/redux": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz",
"integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==",
"dependencies": {
"@babel/runtime": "^7.9.2"
}
},
"node_modules/regenerate": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz",
@ -17185,6 +17243,14 @@
"punycode": "^2.1.0"
}
},
"node_modules/use-sync-external-store": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
"integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@ -21400,6 +21466,11 @@
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.2.tgz",
"integrity": "sha512-F5DIZ36YVLE+PN+Zwws4kJogq47hNgX3Nx6WyDJ3kcplxyke3XIzB8uK5n/Lpm1HBsbGzd6nmGehL8cPekP+Tg=="
},
"@types/use-sync-external-store": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
},
"@types/ws": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz",
@ -28886,6 +28957,26 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
},
"react-redux": {
"version": "8.1.3",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-8.1.3.tgz",
"integrity": "sha512-n0ZrutD7DaX/j9VscF+uTALI3oUPa/pO4Z3soOBIjuRn/FzVu6aehhysxZCLi6y7duMf52WNZGMl7CtuK5EnRw==",
"requires": {
"@babel/runtime": "^7.12.1",
"@types/hoist-non-react-statics": "^3.3.1",
"@types/use-sync-external-store": "^0.0.3",
"hoist-non-react-statics": "^3.3.2",
"react-is": "^18.0.0",
"use-sync-external-store": "^1.0.0"
},
"dependencies": {
"react-is": {
"version": "18.2.0",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
"integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w=="
}
}
},
"react-refresh": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
@ -29020,6 +29111,14 @@
}
}
},
"redux": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz",
"integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==",
"requires": {
"@babel/runtime": "^7.9.2"
}
},
"regenerate": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz",
@ -30399,6 +30498,12 @@
"punycode": "^2.1.0"
}
},
"use-sync-external-store": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
"integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
"requires": {}
},
"util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

View File

@ -17,7 +17,7 @@
"chart.js": "^4.4.0",
"clsx": "1.1.1",
"cytoscape": "^3.26.0",
"date-fns": "2.28.0",
"date-fns": "^2.28.0",
"history": "5.3.0",
"linq-to-typescript": "^11.0.0",
"nprogress": "0.2.0",
@ -34,9 +34,11 @@
"react-icons": "^4.11.0",
"react-icons-converter": "^1.1.4",
"react-intl": "^6.4.4",
"react-redux": "^8.1.3",
"react-router": "6.3.0",
"react-router-dom": "6.3.0",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"rxjs": "^7.8.1",
"simplytyped": "^3.3.0",
"stylis": "4.1.1",

View File

@ -1,4 +1,4 @@
import { Navigate, Route, Routes } from 'react-router-dom';
import { Navigate, Route, Routes, useNavigate } from 'react-router-dom';
import { CssBaseline } from '@mui/material';
import ThemeProvider from './theme/ThemeProvider';
import React, { lazy, Suspense, useContext, useState } from 'react';
@ -9,15 +9,16 @@ import en from './lang/en.json';
import de from './lang/de.json';
import fr from './lang/fr.json';
import SuspenseLoader from './components/SuspenseLoader';
import { RouteObject } from 'react-router';
import BaseLayout from './layouts/BaseLayout';
import SidebarLayout from './layouts/SidebarLayout';
import { TokenContext } from './contexts/tokenContext';
import ResetPassword from './components/ResetPassword';
import ForgotPassword from './components/ForgotPassword';
import InstallationTabs from './content/dashboards/Installations/index';
import routes from 'src/Resources/routes.json';
import './App.css';
import ForgotPassword from './components/ForgotPassword';
import { axiosConfigWithoutToken } from './Resources/axiosConfig';
import UsersContextProvider from './contexts/UsersContextProvider';
import InstallationsContextProvider from './contexts/InstallationsContextProvider';
function App() {
const context = useContext(UserContext);
@ -25,6 +26,9 @@ function App() {
const tokencontext = useContext(TokenContext);
const { token, setNewToken, removeToken } = tokencontext;
const [forgotPassword, setForgotPassword] = useState(false);
const navigate = useNavigate();
const searchParams = new URLSearchParams(location.search);
const username = searchParams.get('username');
const [language, setLanguage] = useState('en');
const getTranslations = () => {
@ -62,9 +66,26 @@ function App() {
lazy(() => import('src/components/ResetPassword'))
);
const SetNewPassword = Loader(
lazy(() => import('src/components/SetNewPassword'))
);
const Login = Loader(lazy(() => import('src/components/login')));
const Users = Loader(lazy(() => import('src/content/dashboards/Users')));
const loginToResetPassword = () => {
axiosConfigWithoutToken
.post('/Login', null, { params: { username, password: '' } })
.then((response) => {
if (response.data && response.data.token) {
setNewToken(response.data.token);
setUser(response.data.user);
navigate(routes.installations);
}
})
.catch((error) => {});
};
// Status
const Status404 = Loader(
lazy(() => import('src/content/pages/Status/Status404'))
@ -79,61 +100,25 @@ function App() {
lazy(() => import('src/content/pages/Status/Maintenance'))
);
const routesArray: RouteObject[] = [
{
path: '',
element: <BaseLayout />,
children: [
{
path: '/',
element: <Navigate to="installations/" replace />
},
{
path: 'status',
children: [
{
path: '',
element: <Navigate to="404" replace />
},
{
path: '404',
element: <Status404 />
},
{
path: '500',
element: <Status500 />
},
{
path: 'maintenance',
element: <StatusMaintenance />
},
{
path: 'coming-soon',
element: <StatusComingSoon />
}
]
},
{
path: '*',
element: <Status404 />
}
]
}
];
if (forgotPassword) {
return (
<ThemeProvider>
<CssBaseline />
<ForgotPassword resetPassword={resetPassword} />
</ThemeProvider>
);
if (username) {
loginToResetPassword();
}
if (!token) {
return (
<ThemeProvider>
<CssBaseline />
<Login onForgotPassword={onForgotPassword}></Login>
<Routes>
<Route
path={''}
element={<Navigate to={routes.login}></Navigate>}
></Route>
<Route path={routes.login} element={<Login></Login>}></Route>
<Route
path={routes.forgotPassword}
element={<ForgotPassword />}
></Route>
</Routes>
</ThemeProvider>
);
}
@ -142,7 +127,7 @@ function App() {
return (
<ThemeProvider>
<CssBaseline />
<ResetPassword></ResetPassword>
<SetNewPassword></SetNewPassword>
</ThemeProvider>
);
}
@ -156,18 +141,10 @@ function App() {
>
<CssBaseline />
<Routes>
{routesArray.map((route, index) => (
<Route key={index} path={route.path} element={route.element}>
{route.children &&
route.children.map((childRoute, childIndex) => (
<Route
key={childIndex}
path={childRoute.path}
element={childRoute.element}
/>
))}
</Route>
))}
<Route
path={''}
element={<Navigate to={routes.installations}></Navigate>}
></Route>
<Route
path="/"
element={
@ -179,11 +156,18 @@ function App() {
>
<Route
path={routes.installations + '*'}
element={<InstallationTabs />}
element={
<UsersContextProvider>
<InstallationsContextProvider>
<InstallationTabs />
</InstallationsContextProvider>
</UsersContextProvider>
}
/>
<Route path={routes.users + '*'} element={<Users />} />
<Route path="ResetPassword" element={<ResetPassword />}></Route>
<Route path="Login" element={<Login />}></Route>
</Route>
</Routes>
</IntlProvider>

View File

@ -37,7 +37,7 @@ export function findPower(value) {
value = Math.abs(value);
// Calculate the power of 10 that's greater or equal to the absolute value
let exponent = Math.floor(Math.log10(value));
const exponent = Math.floor(Math.log10(value));
// Compute the nearest power of 10
const nearestPowerOf10 = Math.pow(10, exponent);

View File

@ -1,6 +1,6 @@
{
"installation": "installation/",
"liveView": "liveView/",
"live": "live",
"users": "/users/",
"log": "log/",
"installations": "/installations/",
@ -9,6 +9,13 @@
"folder": "folder/",
"manageAccess": "manageAccess/",
"user": "user/",
"tree": "tree",
"list": "list"
"tree": "tree/",
"list": "list/",
"overview": "overview",
"manage": "manage",
"log": "log",
"information": "information",
"configuration": "configuration",
"login": "/login/",
"forgotPassword": "/forgotPassword/"
}

View File

@ -16,12 +16,14 @@ import { TokenContext } from 'src/contexts/tokenContext';
import Avatar from '@mui/material/Avatar';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import axiosConfig from 'src/Resources/axiosConfig';
import { useNavigate } from 'react-router-dom';
import routes from 'src/Resources/routes.json';
interface ForgotPasswordPromps {
resetPassword: () => void;
}
function ForgotPassword(props: ForgotPasswordPromps) {
function ForgotPassword() {
const [username, setUsername] = useState('');
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
@ -35,6 +37,7 @@ function ForgotPassword(props: ForgotPasswordPromps) {
const { currentUser, setUser, removeUser } = context;
const tokencontext = useContext(TokenContext);
const { token, setNewToken, removeToken } = tokencontext;
const navigate = useNavigate();
const handleUsernameChange = (e) => {
const { name, value } = e.target;
@ -43,7 +46,8 @@ function ForgotPassword(props: ForgotPasswordPromps) {
const handleReturn = () => {
setOpen(false);
props.resetPassword();
navigate(routes.login);
//props.resetPassword();
};
const handleSubmit = () => {
@ -72,7 +76,7 @@ function ForgotPassword(props: ForgotPasswordPromps) {
<Container maxWidth="xl" sx={{ pt: 2 }}>
<Grid container>
<Grid item xs={3} container justifyContent="flex-start" mb={2}>
<a href="https://www.innov.energy/de/">
<a href="https://monitor.innov.energy/">
<img src={innovenergyLogo} alt="innovenergy logo" height="100" />
</a>
</Grid>
@ -122,6 +126,12 @@ function ForgotPassword(props: ForgotPasswordPromps) {
margin="normal"
required
sx={{ width: 350 }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleSubmit();
}
}}
/>
{loading && <CircularProgress sx={{ color: '#ffc04d' }} />}

View File

@ -73,7 +73,7 @@ function ResetPassword() {
<Container maxWidth="xl" sx={{ pt: 2 }}>
<Grid container>
<Grid item xs={3} container justifyContent="flex-start" mb={2}>
<a href="https://www.innov.energy/de/">
<a href="https://monitor.innov.energy/">
<img src={innovenergyLogo} alt="innovenergy logo" height="100" />
</a>
</Grid>

View File

@ -23,12 +23,9 @@ import { TokenContext } from 'src/contexts/tokenContext';
import { useNavigate } from 'react-router-dom';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import CheckBoxIcon from '@mui/icons-material/CheckBox';
import routes from 'src/Resources/routes.json';
interface loginPromps {
onForgotPassword: () => void;
}
function Login(props: loginPromps) {
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
@ -43,11 +40,10 @@ function Login(props: loginPromps) {
if (!context) {
return null;
}
const { currentUser, setUser, removeUser } = context;
const { currentUser, setUser, removeUser } = context;
const tokencontext = useContext(TokenContext);
const { token, setNewToken, removeToken } = tokencontext;
const cookies = new Cookies();
const handleUsernameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
@ -61,6 +57,11 @@ function Login(props: loginPromps) {
const handleRememberMeChange = () => {
setRememberMe(!rememberMe);
};
const onForgotPassword = () => {
navigate(routes.forgotPassword);
};
const handleSubmit = () => {
setLoading(true);
axiosConfigWithoutToken
@ -76,7 +77,7 @@ function Login(props: loginPromps) {
cookies.set('rememberedUsername', username, { path: '/' });
cookies.set('rememberedPassword', password, { path: '/' });
}
navigate('/');
navigate(routes.installations);
}
})
.catch((error) => {
@ -91,10 +92,10 @@ function Login(props: loginPromps) {
return (
<>
<Container maxWidth="xl" sx={{ pt: 2 }}>
<Container maxWidth="xl" sx={{ pt: 2 }} className="login">
<Grid container>
<Grid item xs={3} container justifyContent="flex-start" mb={2}>
<a href="https://www.innov.energy/de/">
<a href="https://monitor.innov.energy/">
<img src={innovenergyLogo} alt="innovenergy logo" height="100" />
</a>
</Grid>
@ -113,7 +114,6 @@ function Login(props: loginPromps) {
boxShadow: 24,
p: 6,
position: 'absolute',
top: '30%',
left: '50%',
transform: 'translate(-50%, -50%)'
@ -143,6 +143,12 @@ function Login(props: loginPromps) {
margin="normal"
required
sx={{ width: 350 }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleSubmit();
}
}}
/>
<TextField
@ -155,6 +161,12 @@ function Login(props: loginPromps) {
margin="normal"
required
sx={{ width: 350 }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleSubmit();
}
}}
/>
<FormControlLabel
@ -188,7 +200,7 @@ function Login(props: loginPromps) {
{loading && (
<CircularProgress
sx={{
color: theme.palette.primary.main,
color: '#ffc04d',
marginLeft: '20px'
}}
/>
@ -242,7 +254,7 @@ function Login(props: loginPromps) {
sx={{ color: '#111111' }}
onClick={(e) => {
e.preventDefault();
props.onForgotPassword();
onForgotPassword();
}}
>
Forgot password?

View File

@ -1,6 +1,7 @@
import { TopologyValues } from '../Log/graph.util';
import { Box, CardContent, Container, Grid, TextField } from '@mui/material';
import React from 'react';
import { FormattedMessage } from 'react-intl';
interface ConfigurationProps {
values: TopologyValues;
@ -32,7 +33,12 @@ function Configuration(props: ConfigurationProps) {
>
<div>
<TextField
label="Minimum SoC"
label={
<FormattedMessage
id="minimum_soc"
defaultMessage="Minimum SoC"
/>
}
value={props.values.minimumSoC.values[0].value + ' %'}
fullWidth
/>
@ -40,14 +46,24 @@ function Configuration(props: ConfigurationProps) {
<div>
<TextField
label="Calibration Charge forced"
label={
<FormattedMessage
id="calibration_charge_forced"
defaultMessage="Calibration Charge forced"
/>
}
value={props.values.calibrationChargeForced.values[0].value}
fullWidth
/>
</div>
<div>
<TextField
label="Grid Set Point"
label={
<FormattedMessage
id="grid_set_point"
defaultMessage="Grid Set Point"
/>
}
value={
(
(props.values.gridSetPoint.values[0].value as number) /
@ -59,7 +75,12 @@ function Configuration(props: ConfigurationProps) {
</div>
<div>
<TextField
label="Installed Power DC1010"
label={
<FormattedMessage
id="Installed_Power_DC1010"
defaultMessage="Installed Power DC1010"
/>
}
value={
(
(props.values.installedDcDcPower.values[0]
@ -71,7 +92,12 @@ function Configuration(props: ConfigurationProps) {
</div>
<div>
<TextField
label="Maximum Discharge Power"
label={
<FormattedMessage
id="Maximum_Discharge_Power"
defaultMessage="Maximum Discharge Power"
/>
}
value={
(
(props.values.maximumDischargePower.values[0]
@ -83,7 +109,12 @@ function Configuration(props: ConfigurationProps) {
</div>
<div>
<TextField
label="Number of Batteries"
label={
<FormattedMessage
id="Number_of_Batteries"
defaultMessage="Number of Batteries"
/>
}
value={props.values.battery.values.length - 4}
fullWidth
/>

View File

@ -18,7 +18,6 @@ import CancelIcon from '@mui/icons-material/Cancel';
import { LogContext } from 'src/contexts/LogContextProvider';
import { FormattedMessage } from 'react-intl';
import { useNavigate } from 'react-router-dom';
import routes from 'src/Resources/routes.json';
interface FlatInstallationViewProps {
installations: I_Installation[];
@ -29,7 +28,6 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
const logContext = useContext(LogContext);
const { getStatus } = logContext;
const navigate = useNavigate();
const searchParams = new URLSearchParams(location.search);
const installationId = parseInt(searchParams.get('installation'));
const [selectedInstallation, setSelectedInstallation] = useState<number>(-1);
@ -37,15 +35,9 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
const handleSelectOneInstallation = (installationID: number): void => {
if (selectedInstallation != installationID) {
setSelectedInstallation(installationID);
navigate(
routes.installations +
routes.list +
'?installation=' +
installationID.toString(),
{
replace: true
}
);
navigate(`?installation=${installationID}`, {
replace: true
});
} else {
setSelectedInstallation(-1);
}
@ -88,8 +80,8 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
</TableCell>
<TableCell>
<FormattedMessage
id="order"
defaultMessage="Order Values"
id="orderNumbers"
defaultMessage="Order Numbers"
/>
</TableCell>
<TableCell>
@ -234,6 +226,7 @@ const FlatInstallationView = (props: FlatInstallationViewProps) => {
</TableContainer>
</Card>
</Grid>
{props.installations.map((installation) => (
<Installation
key={installation.id}

View File

@ -1,4 +1,4 @@
import React, { ChangeEvent, useContext, useEffect, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import {
Alert,
Box,
@ -8,9 +8,9 @@ import {
Container,
Grid,
IconButton,
Tab,
Tabs,
Modal,
TextField,
Typography,
useTheme
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material';
@ -18,7 +18,6 @@ import { I_Installation } from 'src/interfaces/InstallationTypes';
import Button from '@mui/material/Button';
import { TokenContext } from 'src/contexts/tokenContext';
import { UserContext } from 'src/contexts/userContext';
import { TabsContainerWrapper } from 'src/layouts/TabsContainerWrapper';
import { InstallationsContext } from 'src/contexts/InstallationsContextProvider';
import AccessContextProvider from 'src/contexts/AccessContextProvider';
import Access from '../ManageAccess/Access';
@ -38,43 +37,12 @@ import Configuration from '../Configuration/Configuration';
import { fetchData } from 'src/content/dashboards/Installations/fetchData';
interface singleInstallationProps {
current_installation: I_Installation;
type: string;
current_installation?: I_Installation;
type?: string;
}
function Installation(props: singleInstallationProps) {
const tabs = [
{
value: 'live',
label: <FormattedMessage id="live" defaultMessage="Live" />
},
{
value: 'overview',
label: <FormattedMessage id="overview" defaultMessage="Overview" />
},
,
{
value: 'manage',
label: <FormattedMessage id="manage" defaultMessage="Access Management" />
},
{
value: 'log',
label: <FormattedMessage id="log" defaultMessage="Log" />
},
{
value: 'information',
label: <FormattedMessage id="information" defaultMessage="Information" />
},
{
value: 'configuration',
label: (
<FormattedMessage id="configuration" defaultMessage="Configuration" />
)
}
];
const theme = useTheme();
const [currentTab, setCurrentTab] = useState<string>('live');
const [formValues, setFormValues] = useState(props.current_installation);
const requiredFields = ['name', 'region', 'location', 'country'];
const context = useContext(UserContext);
@ -100,17 +68,16 @@ function Installation(props: singleInstallationProps) {
const { installationStatus, handleLogWarningOrError, getStatus } = logContext;
const searchParams = new URLSearchParams(location.search);
const installationId = parseInt(searchParams.get('installation'));
const currentTab = searchParams.get('tab');
const [values, setValues] = useState<TopologyValues | null>(null);
const [openModalDeleteInstallation, setOpenModalDeleteInstallation] =
useState(false);
if (formValues == undefined) {
return null;
}
const handleTabsChange = (_event: ChangeEvent<{}>, value: string): void => {
setCurrentTab(value);
setError(false);
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormValues({
@ -127,7 +94,18 @@ function Installation(props: singleInstallationProps) {
const handleDelete = (e) => {
setLoading(true);
setError(false);
setOpenModalDeleteInstallation(true);
};
const deleteInstallationModalHandle = (e) => {
setOpenModalDeleteInstallation(false);
deleteInstallation(formValues, props.type);
setLoading(false);
};
const deleteInstallationModalHandleCancel = (e) => {
setOpenModalDeleteInstallation(false);
setLoading(false);
};
const areRequiredFieldsFilled = () => {
@ -155,8 +133,8 @@ function Installation(props: singleInstallationProps) {
useEffect(() => {
let isMounted = true;
setFormValues(props.current_installation);
setErrorLoadingS3Data(false);
let disconnectedStatusResult = [];
const fetchDataPeriodically = async () => {
const now = UnixTime.now().earlier(TimeSpan.fromSeconds(20));
@ -165,9 +143,6 @@ function Installation(props: singleInstallationProps) {
try {
const res = await fetchData(now, s3Credentials);
if (installationId == 2) {
console.log('Fetched data from unix timestamp ' + now);
}
if (!isMounted) {
return;
}
@ -176,8 +151,22 @@ function Installation(props: singleInstallationProps) {
const newErrors: Notification[] = [];
if (res === FetchResult.notAvailable || res === FetchResult.tryLater) {
setErrorLoadingS3Data(true);
handleLogWarningOrError(props.current_installation.id, -1);
disconnectedStatusResult.unshift(-1);
disconnectedStatusResult = disconnectedStatusResult.slice(0, 5);
let i = 0;
//If at least one status value shows an error, then show error
for (i; i < disconnectedStatusResult.length; i++) {
if (disconnectedStatusResult[i] != -1) {
break;
}
}
if (i === disconnectedStatusResult.length) {
setErrorLoadingS3Data(true);
}
} else {
setErrorLoadingS3Data(false);
setValues(
@ -237,9 +226,15 @@ function Installation(props: singleInstallationProps) {
if (newErrors.length > 0) {
handleLogWarningOrError(props.current_installation.id, 2);
disconnectedStatusResult.unshift(2);
disconnectedStatusResult = disconnectedStatusResult.slice(0, 5);
} else if (newWarnings.length > 0) {
disconnectedStatusResult.unshift(1);
disconnectedStatusResult = disconnectedStatusResult.slice(0, 5);
handleLogWarningOrError(props.current_installation.id, 1);
} else {
disconnectedStatusResult.unshift(0);
disconnectedStatusResult = disconnectedStatusResult.slice(0, 5);
handleLogWarningOrError(props.current_installation.id, 0);
}
}
@ -259,291 +254,394 @@ function Installation(props: singleInstallationProps) {
if (installationId == props.current_installation.id) {
return (
<Grid item xs={12} md={12}>
<TabsContainerWrapper>
<Tabs
onChange={handleTabsChange}
value={currentTab}
variant="scrollable"
scrollButtons="auto"
textColor="primary"
indicatorColor="primary"
<>
{openModalDeleteInstallation && (
<Modal
open={openModalDeleteInstallation}
onClose={() => setOpenModalDeleteInstallation(false)}
aria-labelledby="error-modal"
aria-describedby="error-modal-description"
>
{tabs.map((tab) => (
<Tab key={tab.value} label={tab.label} value={tab.value} />
))}
</Tabs>
</TabsContainerWrapper>
<Card variant="outlined">
<Grid
container
direction="row"
justifyContent="center"
alignItems="stretch"
spacing={0}
>
{currentTab === 'information' && (
<Container maxWidth="xl">
<Grid
container
direction="row"
justifyContent="center"
alignItems="stretch"
spacing={3}
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 350,
bgcolor: 'background.paper',
borderRadius: 4,
boxShadow: 24,
p: 4,
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}}
>
<Typography
variant="body1"
gutterBottom
sx={{ fontWeight: 'bold' }}
>
Do you want to delete this installation?
</Typography>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: 10
}}
>
<Button
sx={{
marginTop: 2,
textTransform: 'none',
bgcolor: '#ffc04d',
color: '#111111',
'&:hover': { bgcolor: '#f7b34d' }
}}
onClick={deleteInstallationModalHandle}
>
<Grid item xs={12} md={12}>
<CardContent>
<Box
component="form"
sx={{
'& .MuiTextField-root': { m: 1, width: '50ch' }
}}
noValidate
autoComplete="off"
>
<div>
<TextField
label={
<FormattedMessage
id="customerName"
defaultMessage="Customer Name"
/>
}
name="name"
value={formValues.name}
onChange={handleChange}
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="region"
defaultMessage="Region"
/>
}
name="region"
value={formValues.region}
onChange={handleChange}
variant="outlined"
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="location"
defaultMessage="Location"
/>
}
name="location"
value={formValues.location}
onChange={handleChange}
variant="outlined"
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="country"
defaultMessage="Country"
/>
}
name="country"
value={formValues.country}
onChange={handleChange}
variant="outlined"
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="orderNumbers"
defaultMessage="Order Numbers"
/>
}
name="orderNumbers"
value={formValues.orderNumbers}
onChange={handleChange}
variant="outlined"
fullWidth
/>
</div>
Delete
</Button>
<Button
sx={{
marginTop: 2,
marginLeft: 2,
textTransform: 'none',
bgcolor: '#ffc04d',
color: '#111111',
'&:hover': { bgcolor: '#f7b34d' }
}}
onClick={deleteInstallationModalHandleCancel}
>
Cancel
</Button>
</div>
</Box>
</Modal>
)}
{currentUser.hasWriteAccess && (
<>
<div>
<TextField
label="S3 Write Key"
name="s3writekey"
value={formValues.s3WriteKey}
variant="outlined"
fullWidth
/>
</div>
<Grid item xs={12} md={12}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<Typography
fontWeight="bold"
color="text.primary"
noWrap
sx={{
marginTop: '-20px',
marginBottom: '10px',
fontSize: '14px'
}}
>
<FormattedMessage
id="installation_name_simple"
defaultMessage="Installation Name:"
/>
</Typography>
<Typography
fontWeight="bold"
color="orange"
noWrap
sx={{
marginTop: '-20px',
marginBottom: '10px',
marginLeft: '5px',
fontSize: '14px'
}}
>
{props.current_installation.name}
</Typography>
</div>
<div>
<TextField
label="S3 Write Secret Key"
name="s3writesecretkey"
value={formValues.s3WriteSecret}
variant="outlined"
fullWidth
/>
</div>
<div>
<TextField
label="S3 Bucket Name"
name="s3writesecretkey"
value={
formValues.id +
'-3e5b3069-214a-43ee-8d85-57d72000c19d'
}
variant="outlined"
fullWidth
/>
</div>
</>
)}
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: 10
<Card variant="outlined">
<Grid
container
direction="row"
justifyContent="center"
alignItems="stretch"
spacing={0}
>
{currentTab === 'information' && (
<Container maxWidth="xl">
<Grid
container
direction="row"
justifyContent="center"
alignItems="stretch"
spacing={3}
>
<Grid item xs={12} md={12}>
<CardContent>
<Box
component="form"
sx={{
'& .MuiTextField-root': { m: 1, width: '50ch' }
}}
noValidate
autoComplete="off"
>
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleSubmit}
sx={{
marginLeft: '10px'
}}
disabled={!areRequiredFieldsFilled()}
>
<FormattedMessage
id="applyChanges"
defaultMessage="Apply Changes"
/>
</Button>
)}
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleDelete}
sx={{
marginLeft: '10px'
}}
>
<FormattedMessage
id="deleteInstallation"
defaultMessage="Delete Installation"
/>
</Button>
)}
{loading && (
<CircularProgress
sx={{
color: theme.palette.primary.main,
marginLeft: '20px'
}}
<div>
<TextField
label={
<FormattedMessage
id="customerName"
defaultMessage="Customer Name"
/>
}
name="name"
value={formValues.name}
onChange={handleChange}
fullWidth
required
error={formValues.name === ''}
/>
)}
{error && (
<Alert
severity="error"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center'
}}
>
<FormattedMessage
id="errorOccured"
defaultMessage="An error has occurred"
/>
<IconButton
color="inherit"
size="small"
onClick={() => setError(false)}
sx={{ marginLeft: '4px' }}
>
<CloseIcon fontSize="small" />
</IconButton>
</Alert>
)}
{updated && (
<Alert
severity="success"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center'
}}
>
<FormattedMessage
id="successfullyUpdated"
defaultMessage="Successfully updated"
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="region"
defaultMessage="Region"
/>
}
name="region"
value={formValues.region}
onChange={handleChange}
variant="outlined"
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="location"
defaultMessage="Location"
/>
}
name="location"
value={formValues.location}
onChange={handleChange}
variant="outlined"
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="country"
defaultMessage="Country"
/>
}
name="country"
value={formValues.country}
onChange={handleChange}
variant="outlined"
fullWidth
required
error={formValues.name === ''}
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="orderNumbers"
defaultMessage="Order Numbers"
/>
}
name="orderNumbers"
value={formValues.orderNumbers}
onChange={handleChange}
variant="outlined"
fullWidth
/>
</div>
<div>
<TextField
label={
<FormattedMessage
id="installation_name"
defaultMessage="Installation Name"
/>
}
name="installationName"
value={formValues.installationName}
onChange={handleChange}
variant="outlined"
fullWidth
/>
</div>
<IconButton
color="inherit"
size="small"
onClick={() => setUpdated(false)} // Set error state to false on click
sx={{ marginLeft: '4px' }}
>
<CloseIcon fontSize="small" />
</IconButton>
</Alert>
{currentUser.hasWriteAccess && (
<>
<div>
<TextField
label="S3 Write Key"
name="s3writekey"
value={formValues.s3WriteKey}
variant="outlined"
fullWidth
/>
</div>
<div>
<TextField
label="S3 Write Secret Key"
name="s3writesecretkey"
value={formValues.s3WriteSecret}
variant="outlined"
fullWidth
/>
</div>
<div>
<TextField
label="S3 Bucket Name"
name="s3writesecretkey"
value={
formValues.id +
'-3e5b3069-214a-43ee-8d85-57d72000c19d'
}
variant="outlined"
fullWidth
/>
</div>
</>
)}
</div>
</Box>
</CardContent>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: 10
}}
>
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleDelete}
sx={{
marginLeft: '10px'
}}
>
<FormattedMessage
id="deleteInstallation"
defaultMessage="Delete Installation"
/>
</Button>
)}
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleSubmit}
sx={{
marginLeft: '10px'
}}
disabled={!areRequiredFieldsFilled()}
>
<FormattedMessage
id="applyChanges"
defaultMessage="Apply Changes"
/>
</Button>
)}
{loading && (
<CircularProgress
sx={{
color: theme.palette.primary.main,
marginLeft: '20px'
}}
/>
)}
{error && (
<Alert
severity="error"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center'
}}
>
<FormattedMessage
id="errorOccured"
defaultMessage="An error has occurred"
/>
<IconButton
color="inherit"
size="small"
onClick={() => setError(false)}
sx={{ marginLeft: '4px' }}
>
<CloseIcon fontSize="small" />
</IconButton>
</Alert>
)}
{updated && (
<Alert
severity="success"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center'
}}
>
<FormattedMessage
id="successfullyUpdated"
defaultMessage="Successfully updated"
/>
<IconButton
color="inherit"
size="small"
onClick={() => setUpdated(false)} // Set error state to false on click
sx={{ marginLeft: '4px' }}
>
<CloseIcon fontSize="small" />
</IconButton>
</Alert>
)}
</div>
</Box>
</CardContent>
</Grid>
</Grid>
</Grid>
</Container>
)}
{currentTab === 'overview' && (
<Overview s3Credentials={s3Credentials}></Overview>
)}
{currentTab === 'configuration' && currentUser.hasWriteAccess && (
<Configuration values={values}></Configuration>
)}
{currentTab === 'manage' && currentUser.hasWriteAccess && (
<AccessContextProvider>
<Access
currentResource={formValues}
resourceType={props.type}
></Access>
</AccessContextProvider>
)}
{currentTab === 'live' && <Topology values={values}></Topology>}
{currentTab === 'log' && (
<Log
warnings={warnings}
errors={errors}
errorLoadingS3Data={errorLoadingS3Data}
></Log>
)}
</Grid>
</Card>
</Grid>
</Container>
)}
{currentTab === 'overview' && (
<Overview s3Credentials={s3Credentials}></Overview>
)}
{currentTab === 'configuration' && currentUser.hasWriteAccess && (
<Configuration values={values}></Configuration>
)}
{currentTab === 'manage' && currentUser.hasWriteAccess && (
<AccessContextProvider>
<Access
currentResource={formValues}
resourceType={props.type}
></Access>
</AccessContextProvider>
)}
{currentTab === 'live' && <Topology values={values}></Topology>}
{currentTab === 'log' && (
<Log
warnings={warnings}
errors={errors}
errorLoadingS3Data={errorLoadingS3Data}
></Log>
)}
</Grid>
</Card>
</Grid>
</>
);
} else {
return null;

View File

@ -1,4 +1,4 @@
import React, { useContext, useEffect, useState } from 'react';
import React, { useEffect, useState } from 'react';
import {
FormControl,
Grid,
@ -6,34 +6,32 @@ import {
TextField,
useTheme
} from '@mui/material';
import { InstallationsContext } from 'src/contexts/InstallationsContextProvider';
import SearchTwoToneIcon from '@mui/icons-material/SearchTwoTone';
import FlatInstallationView from 'src/content/dashboards/Installations/FlatInstallationView';
import LogContextProvider from 'src/contexts/LogContextProvider';
import LogContextProvider from '../../../contexts/LogContextProvider';
import { I_Installation } from '../../../interfaces/InstallationTypes';
function InstallationSearch() {
interface installationSearchProps {
installations: I_Installation[];
}
function InstallationSearch(props: installationSearchProps) {
const theme = useTheme();
const [searchTerm, setSearchTerm] = useState('');
const { installations, fetchAllInstallations } =
useContext(InstallationsContext);
const searchParams = new URLSearchParams(location.search);
const installationId = parseInt(searchParams.get('installation'));
useEffect(() => {
fetchAllInstallations();
}, []);
const [filteredData, setFilteredData] = useState(installations);
const [filteredData, setFilteredData] = useState(props.installations);
useEffect(() => {
const filtered = installations.filter(
const filtered = props.installations.filter(
(item) =>
item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
item.location.toLowerCase().includes(searchTerm.toLowerCase())
);
setFilteredData(filtered);
}, [searchTerm, installations]);
}, [searchTerm, props.installations]);
return (
<>
@ -41,7 +39,7 @@ function InstallationSearch() {
<Grid
item
xs={12}
md={4}
md={6}
sx={{ display: !installationId ? 'block' : 'none' }}
>
<FormControl variant="outlined">

View File

@ -1,19 +0,0 @@
import { Box, Grid, useTheme } from '@mui/material';
import InstallationsContextProvider from 'src/contexts/InstallationsContextProvider';
import InstallationSearch from './InstallationSearch';
function FlatView() {
const theme = useTheme();
return (
<InstallationsContextProvider>
<Grid item xs={12}>
<Box p={4}>
<InstallationSearch />
</Box>
</Grid>
</InstallationsContextProvider>
);
}
export default FlatView;

View File

@ -1,10 +1,9 @@
import React, { ChangeEvent, useEffect, useState } from 'react';
import React, { ChangeEvent, useContext, useEffect, useState } from 'react';
import Footer from 'src/components/Footer';
import { Card, Container, Grid, Tab, Tabs, useTheme } from '@mui/material';
import { Box, Card, Container, Grid, Tab, Tabs, useTheme } from '@mui/material';
import ListIcon from '@mui/icons-material/List';
import AccountTreeIcon from '@mui/icons-material/AccountTree';
import { TabsContainerWrapper } from 'src/layouts/TabsContainerWrapper';
import UsersContextProvider from 'src/contexts/UsersContextProvider';
import {
Link,
Route,
@ -12,50 +11,220 @@ import {
useLocation,
useNavigate
} from 'react-router-dom';
import FlatView from './flatView';
import TreeView from '../Tree/treeView';
import routes from 'src/Resources/routes.json';
import InstallationSearch from './InstallationSearch';
import { FormattedMessage } from 'react-intl';
import { UserContext } from '../../../contexts/userContext';
import { InstallationsContext } from '../../../contexts/InstallationsContextProvider';
import LogContextProvider from '../../../contexts/LogContextProvider';
import Installation from './Installation';
function InstallationTabs() {
const theme = useTheme();
const location = useLocation();
const navigate = useNavigate();
const tabs = [
{
value: 'list',
label: 'Flat view',
icon: <ListIcon id="mode-toggle-button-list-icon" />
},
{
value: 'tree',
label: 'Tree view',
icon: <AccountTreeIcon id="mode-toggle-button-tree-icon" />
}
];
const searchParams = new URLSearchParams(location.search);
const installationId = parseInt(searchParams.get('installation'));
const [singleInstallationID, setSingleInstallationID] = useState(-1);
const context = useContext(UserContext);
const { currentUser, setUser } = context;
const [currentTab, setCurrentTab] = useState<string>('list');
const { installations, fetchAllInstallations } =
useContext(InstallationsContext);
useEffect(() => {
//console.log(location.pathname);
if (
location.pathname === '/installations' ||
location.pathname === '/installations/'
) {
navigate(routes.installations + routes.list, {
if (installations.length === 0) {
fetchAllInstallations();
}
if (installations.length === 1) {
navigate(`list?installation=${installations[0].id}&tab=live`, {
replace: true
});
} else if (location.pathname === '/installations/tree') {
setCurrentTab('tree');
setCurrentTab('live');
} else {
if (
location.pathname === '/installations' ||
location.pathname === '/installations/'
) {
navigate(routes.installations + routes.list, {
replace: true
});
} else if (location.pathname === '/installations/tree/') {
setCurrentTab('tree');
} else if (location.pathname === '/installations/list/') {
setCurrentTab('list');
}
if (installationId) {
navigate(`?installation=${installationId}&tab=live`, {
replace: true
});
setCurrentTab('live');
}
}
}, [location.pathname, navigate]);
}, [location.pathname, navigate, installationId, installations]);
const handleTabsChange = (_event: ChangeEvent<{}>, value: string): void => {
setCurrentTab(value);
navigate(value);
};
return (
<UsersContextProvider>
<Container maxWidth="xl" sx={{ marginTop: '20px' }}>
const singleInstallationTabs = currentUser.hasWriteAccess
? [
{
value: 'live',
label: <FormattedMessage id="live" defaultMessage="Live" />
},
{
value: 'overview',
label: <FormattedMessage id="overview" defaultMessage="Overview" />
},
,
{
value: 'manage',
label: (
<FormattedMessage id="manage" defaultMessage="Access Management" />
)
},
{
value: 'log',
label: <FormattedMessage id="log" defaultMessage="Log" />
},
{
value: 'information',
label: (
<FormattedMessage id="information" defaultMessage="Information" />
)
},
{
value: 'configuration',
label: (
<FormattedMessage
id="configuration"
defaultMessage="Configuration"
/>
)
}
]
: [
{
value: 'live',
label: <FormattedMessage id="live" defaultMessage="Live" />
},
{
value: 'overview',
label: <FormattedMessage id="overview" defaultMessage="Overview" />
},
,
{
value: 'log',
label: <FormattedMessage id="log" defaultMessage="Log" />
},
{
value: 'information',
label: (
<FormattedMessage id="information" defaultMessage="Information" />
)
}
];
const tabs = installationId
? currentUser.hasWriteAccess
? [
{
value: 'list',
icon: <ListIcon id="mode-toggle-button-list-icon" />
},
{
value: 'tree',
icon: <AccountTreeIcon id="mode-toggle-button-tree-icon" />
},
{
value: 'live',
label: <FormattedMessage id="live" defaultMessage="Live" />
},
{
value: 'overview',
label: <FormattedMessage id="overview" defaultMessage="Overview" />
},
,
{
value: 'manage',
label: (
<FormattedMessage
id="manage"
defaultMessage="Access Management"
/>
)
},
{
value: 'log',
label: <FormattedMessage id="log" defaultMessage="Log" />
},
{
value: 'information',
label: (
<FormattedMessage id="information" defaultMessage="Information" />
)
},
{
value: 'configuration',
label: (
<FormattedMessage
id="configuration"
defaultMessage="Configuration"
/>
)
}
]
: [
{
value: 'list',
icon: <ListIcon id="mode-toggle-button-list-icon" />
},
{
value: 'tree',
icon: <AccountTreeIcon id="mode-toggle-button-tree-icon" />
},
{
value: 'live',
label: <FormattedMessage id="live" defaultMessage="Live" />
},
{
value: 'overview',
label: <FormattedMessage id="overview" defaultMessage="Overview" />
},
,
{
value: 'log',
label: <FormattedMessage id="log" defaultMessage="Log" />
},
{
value: 'information',
label: (
<FormattedMessage id="information" defaultMessage="Information" />
)
}
]
: [
{
value: 'list',
icon: <ListIcon id="mode-toggle-button-list-icon" />
},
{
value: 'tree',
icon: <AccountTreeIcon id="mode-toggle-button-tree-icon" />
}
];
return installations.length > 1 ? (
<>
<Container maxWidth="xl" sx={{ marginTop: '20px' }} className="mainframe">
<TabsContainerWrapper>
<Tabs
onChange={handleTabsChange}
@ -71,7 +240,12 @@ function InstallationTabs() {
value={tab.value}
icon={tab.icon}
component={Link}
to={routes[tab.value]}
label={tab.label}
to={
tab.value === 'list' || tab.value === 'tree'
? routes[tab.value]
: `?installation=${installationId}&tab=${routes[tab.value]}`
}
/>
))}
</Tabs>
@ -85,15 +259,79 @@ function InstallationTabs() {
spacing={0}
>
<Routes>
<Route path={routes.list + '*'} element={<FlatView />} />
<Route
path={routes.list + '*'}
element={
<Grid item xs={12}>
<Box p={4}>
<InstallationSearch installations={installations} />
</Box>
</Grid>
}
/>
<Route path={routes.tree + '*'} element={<TreeView />} />
</Routes>
</Grid>
</Card>
</Container>
<Footer />
</UsersContextProvider>
);
</>
) : installations.length === 1 ? (
<>
<Container maxWidth="xl" sx={{ marginTop: '20px' }} className="mainframe">
<TabsContainerWrapper>
<Tabs
onChange={handleTabsChange}
value={currentTab}
variant="scrollable"
scrollButtons="auto"
textColor="primary"
indicatorColor="primary"
>
{singleInstallationTabs.map((tab) => (
<Tab
key={tab.value}
value={tab.value}
component={Link}
label={tab.label}
to={`?installation=${installations[0].id}&tab=${
routes[tab.value]
}`}
/>
))}
</Tabs>
</TabsContainerWrapper>
<Card variant="outlined">
<Grid
container
direction="row"
justifyContent="center"
alignItems="stretch"
spacing={0}
>
<Routes>
<Route
path={routes.list + '*'}
element={
<Grid item xs={12}>
<Box p={4}>
<LogContextProvider>
<Installation
current_installation={installations[0]}
type="installation"
></Installation>
</LogContextProvider>
</Box>
</Grid>
}
/>
</Routes>
</Grid>
</Card>
</Container>
<Footer />
</>
) : null;
}
export default InstallationTabs;

View File

@ -66,6 +66,8 @@ function installationForm(props: installationFormProps) {
return true;
};
const isMobile = window.innerWidth <= 1490;
return (
<>
<Modal
@ -77,10 +79,10 @@ function installationForm(props: installationFormProps) {
<Box
sx={{
position: 'absolute',
top: '30%',
top: isMobile ? '50%' : '30%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 600,
width: 500,
bgcolor: 'background.paper',
borderRadius: 4,
boxShadow: 24,

View File

@ -34,10 +34,10 @@ function Log(props: LogProps) {
<Grid container>
<Grid item xs={12} md={12}>
{(props.errors.length > 0 || props.warnings.length > 0) && (
<Card>
<Card sx={{ marginTop: '10px' }}>
<Divider />
<TableContainer>
<Table sx={{ height: 10 }}>
<Table>
<TableHead>
<TableRow>
<TableCell>
@ -82,7 +82,7 @@ function Log(props: LogProps) {
color="text.primary"
gutterBottom
noWrap
sx={{ marginTop: '10px' }}
sx={{ marginTop: '5px' }}
>
{error.device}
</Typography>
@ -94,7 +94,7 @@ function Log(props: LogProps) {
color="text.primary"
gutterBottom
noWrap
sx={{ marginTop: '10px' }}
sx={{ marginTop: '5px' }}
>
{error.description}
</Typography>
@ -106,7 +106,7 @@ function Log(props: LogProps) {
color="text.primary"
gutterBottom
noWrap
sx={{ marginTop: '10px' }}
sx={{ marginTop: '5px' }}
>
{error.date}
</Typography>
@ -118,7 +118,7 @@ function Log(props: LogProps) {
color="text.primary"
gutterBottom
noWrap
sx={{ marginTop: '10px' }}
sx={{ marginTop: '5px' }}
>
{error.time}
</Typography>
@ -202,11 +202,9 @@ function Log(props: LogProps) {
<Alert
severity="error"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center',
marginTop: '20px',
marginBottom: '20px'
marginTop: '20px'
}}
>
<FormattedMessage
@ -227,7 +225,6 @@ function Log(props: LogProps) {
<Alert
severity="error"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center',
marginTop: '20px'
@ -249,10 +246,10 @@ function Log(props: LogProps) {
<Alert
severity="error"
sx={{
ml: 1,
display: 'flex',
alignItems: 'center'
alignItems: 'center',
//marginBottom: '20px'
marginTop: '20px'
}}
>
<FormattedMessage

View File

@ -35,6 +35,15 @@ export type BoxData = {
};
export type TopologyValues = {
gridBox: BoxData;
pvOnAcGridBox: BoxData;
loadOnAcGridBox: BoxData;
pvOnIslandBusBox: BoxData;
loadOnIslandBusBox: BoxData;
pvOnDcBox: BoxData;
loadOnDcBox: BoxData;
batteryBox: BoxData;
grid: BoxData;
gridToAcInConnection: BoxData;
gridBus: BoxData;
@ -64,6 +73,15 @@ export type TopologyValues = {
type TopologyPaths = { [key in keyof TopologyValues]: string[] };
export const topologyPaths: TopologyPaths = {
gridBox: ['/Config/Devices/GridMeterIp/DeviceState'],
pvOnAcGridBox: ['/Config/Devices/PvOnAcGrid/DeviceState'],
loadOnAcGridBox: ['/Config/Devices/LoadOnAcGrid/DeviceState'],
pvOnIslandBusBox: ['/Config/Devices/PvOnAcIsland/DeviceState'],
loadOnIslandBusBox: ['/Config/Devices/IslandBusLoadMeterIp/DeviceState'],
pvOnDcBox: ['/Config/Devices/PvOnDc/DeviceState'],
loadOnDcBox: ['/Config/Devices/LoadOnDc/DeviceState'],
batteryBox: ['/Config/Devices/BatteryIp/DeviceState'],
grid: [
'/GridMeter/Ac/L1/Power/Active',
'/GridMeter/Ac/L2/Power/Active',
@ -86,7 +104,7 @@ export const topologyPaths: TopologyPaths = {
'/AcDc/Ac/L2/Power/Active',
'/AcDc/Ac/L3/Power/Active'
],
islandBusToLoadOnIslandBusConnection: ['/LoadOnAcIsland/Power/Active'],
islandBusToLoadOnIslandBusConnection: ['/LoadOnAcIsland/Ac/Power/Active'],
islandBusToInverter: ['/AcDc/Dc/Power'],
pvOnIslandBusToIslandBusConnection: ['/PvOnAcIsland/Power/Active'],
@ -104,8 +122,8 @@ export const topologyPaths: TopologyPaths = {
dcBusToLoadOnDcConnection: ['/LoadOnDc/Power'],
dcDc: ['/DcDc/Dc/Battery/Voltage'],
dcDCToBatteryConnection: ['/Battery/Dc/Power'],
dcDCToBatteryConnection: ['/DcDc/Dc/Link/Power'],
battery: [
'/Battery/Soc',
'/Battery/Dc/Voltage',
@ -124,7 +142,7 @@ export const topologyPaths: TopologyPaths = {
],
minimumSoC: ['/Config/MinSoc'],
installedDcDcPower: ['/DcDc/SystemControl/TargetSlave'],
installedDcDcPower: ['/DcDc/SystemControl/NumberOfConnectedSlaves'],
gridSetPoint: ['/Config/GridSetPoint'],
maximumDischargePower: ['/Config/MaxBatteryDischargingCurrent'],
calibrationChargeForced: ['/Config/ForceCalibrationCharge']
@ -138,14 +156,10 @@ export const extractValues = (
for (const topologyKey of Object.keys(topologyPaths)) {
const paths = topologyPaths[topologyKey];
let topologyValues: { unit: string; value: string | number }[] = [];
//console.log('paths is ', paths);
// Check if any of the specified paths exist in the dataRecord
for (const path of paths) {
//console.log(' path is ', path);
if (timeSeriesData.value.hasOwnProperty(path)) {
//console.log('matching path is ', path);
//console.log(timeSeriesData.value[path]);
topologyValues.push({
unit: timeSeriesData.value[path].unit,
value: timeSeriesData.value[path].value
@ -179,7 +193,19 @@ export const getAmount = (
highestConnectionValue: number,
values: I_BoxDataValue[]
) => {
return Math.abs(values[0].value as number) / highestConnectionValue;
// console.log(
// 'value=',
// Math.abs(values[0].value as number),
// 'highest is',
// highestConnectionValue,
// 'and amount is ',
// parseFloat(
// (Math.abs(values[0].value as number) / highestConnectionValue).toFixed(1)
// )
// );
return parseFloat(
(Math.abs(values[0].value as number) / highestConnectionValue).toFixed(1)
);
};
export const createTimes = (
@ -187,9 +213,13 @@ export const createTimes = (
numberOfNodes: number
): UnixTime[] => {
const oneSpan = range.duration.divide(numberOfNodes);
//console.log(oneSpan);
const roundedRange = TimeRange.fromTimes(
range.start.round(oneSpan),
range.end.round(oneSpan)
);
return roundedRange.sample(oneSpan);
const unixTimes = range.sample(oneSpan);
return unixTimes;
};

View File

@ -2,21 +2,45 @@
import { ApexOptions } from 'apexcharts';
import { chartInfoInterface } from 'src/interfaces/Chart';
import { findPower, formatPowerForGraph } from '../../../Resources/formatPower';
import { findPower, formatPowerForGraph } from 'src/Resources/formatPower';
import { addHours, format } from 'date-fns';
export const getChartOptions = (chartInfo: chartInfoInterface): ApexOptions => {
// Custom datetime formatter for GMT+2
const customDatetimeFormatter = (timestamp, options) => {
const gmtDate = new Date(timestamp); // Convert Unix timestamp to milliseconds
const gmtPlus2Date = addHours(gmtDate, 4); // Add 2 hours to convert to GMT+2
// Use the specified options to format the date and time
const year = format(gmtDate, 'yyyy');
const month = format(gmtDate, "MMM 'yy");
const day = format(gmtDate, 'dd MMM');
const hour = format(gmtDate, 'HH:mm');
const minute = format(gmtDate, 'mm');
// Return the formatted date and time based on the provided options
return ` ${hour}:${minute}`;
};
const chartOptions: ApexOptions = {
chart: {
id: 'area-datetime',
toolbar: {
show: false
},
type: 'area',
height: 350,
zoom: {
autoScaleYaxis: false
}
},
// markers: {
// size: 1,
// strokeColors: 'black'
// },
dataLabels: {
enabled: false
},
fill: {
type: 'gradient',
gradient: {
@ -36,7 +60,8 @@ export const getChartOptions = (chartInfo: chartInfoInterface): ApexOptions => {
year: 'yyyy',
month: "MMM 'yy",
day: 'dd MMM',
hour: 'HH:mm'
hour: 'HH:mm',
minute: 'mm'
}
}
},
@ -45,11 +70,19 @@ export const getChartOptions = (chartInfo: chartInfoInterface): ApexOptions => {
width: 2
},
yaxis: {
min: chartInfo.min > 0 ? 0 : undefined,
min:
chartInfo.min >= 0
? 0
: chartInfo.max <= 0
? Math.ceil(chartInfo.min / findPower(chartInfo.min).value) *
findPower(chartInfo.min).value
: undefined,
max:
chartInfo.min > 0
? Math.round(chartInfo.max / findPower(chartInfo.max).value) *
chartInfo.min >= 0
? Math.ceil(chartInfo.max / findPower(chartInfo.max).value) *
findPower(chartInfo.max).value
: chartInfo.max <= 0
? 0
: undefined,
title: {
text: chartInfo.unit,
@ -61,30 +94,26 @@ export const getChartOptions = (chartInfo: chartInfoInterface): ApexOptions => {
rotate: 0
},
labels: {
formatter:
chartInfo.min > 0
? function (value: number) {
return formatPowerForGraph(
value,
chartInfo.max
).value.toString();
}
: function (value: number) {
return formatPowerForGraph(
value,
chartInfo.max
).value.toString();
}
formatter: function (value: number) {
return formatPowerForGraph(
value,
Math.max(Math.abs(chartInfo.max), Math.abs(chartInfo.min))
).value.toString();
}
}
},
tooltip: {
x: {
format: 'dd MMM HH:mm'
format: 'dd MMM HH:mm:ss'
},
y: {
formatter: function (val, opts) {
return (
formatPowerForGraph(val, chartInfo.max).value.toFixed(2) +
formatPowerForGraph(
val,
Math.max(Math.abs(chartInfo.max), Math.abs(chartInfo.min))
).value.toFixed(2) +
' ' +
chartInfo.unit
);

View File

@ -7,16 +7,24 @@ import {
useTheme
} from '@mui/material';
import ReactApexChart from 'react-apexcharts';
import { useEffect, useMemo, useState } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import DataCache from 'src/dataCache/dataCache';
import { TimeSpan, UnixTime } from 'src/dataCache/time';
import { BehaviorSubject, startWith, throttleTime, withLatestFrom } from 'rxjs';
import { TimeRange, TimeSpan, UnixTime } from 'src/dataCache/time';
import {
BehaviorSubject,
combineLatest,
startWith,
tap,
throttleTime
} from 'rxjs';
import { RecordSeries } from 'src/dataCache/data';
import { createTimes } from '../Log/graph.util';
import { I_S3Credentials } from 'src/interfaces/S3Types';
import { getChartOptions } from './chartOptions';
import { chartDataInterface, overviewInterface } from 'src/interfaces/Chart';
import { fetchData } from 'src/content/dashboards/Installations/fetchData';
import Button from '@mui/material/Button';
import { FormattedMessage } from 'react-intl';
const prefixes = ['', 'k', 'M', 'G', 'T'];
const MAX_NUMBER = 9999999;
@ -27,9 +35,12 @@ interface OverviewProps {
function Overview(props: OverviewProps) {
const theme = useTheme();
const timeRange = createTimes(
UnixTime.now().rangeBefore(TimeSpan.fromDays(1)),
200
const numOfPointsToFetch = 100;
const [timeRange, setTimeRange] = useState(
createTimes(
UnixTime.now().rangeBefore(TimeSpan.fromDays(1)),
numOfPointsToFetch
)
);
const [chartData, setChartData] = useState<chartDataInterface>({
@ -102,38 +113,49 @@ function Overview(props: OverviewProps) {
magnitude: 0,
unit: '',
min: MAX_NUMBER,
max: 0
max: -MAX_NUMBER
};
});
console.log(input);
input.forEach((item) => {
const csvContent = item.value;
pathsToSearch.forEach((path) => {
if (csvContent && csvContent[path]) {
if (csvContent) {
const timestamp = item.time.ticks * 1000;
const value = csvContent[path];
// const result: { magnitude: number; value: number } = formatPower(
// value.value
// );
if (value.value < overviewData[path].min) {
overviewData[path].min = value.value;
}
if (value.value > overviewData[path].max) {
overviewData[path].max = value.value;
}
const adjustedTimestamp = new Date(timestamp);
adjustedTimestamp.setHours(adjustedTimestamp.getHours() + 2);
// if (result.magnitude > result.magnitude) {
// overviewData[path].magnitude = result.magnitude;
// }
data[path].push([timestamp, value.value]);
if (csvContent[path]) {
const value = csvContent[path];
if (value.value < overviewData[path].min) {
overviewData[path].min = value.value;
}
if (value.value > overviewData[path].max) {
overviewData[path].max = value.value;
}
data[path].push([adjustedTimestamp, value.value]);
} else {
//data[path].push([adjustedTimestamp, null]);
}
} else {
// data[path].push([
// addHours(new Date(item.time.ticks * 1000), 2),
// null
// ]);
}
});
});
pathsToSearch.forEach((path) => {
let value = overviewData[path].max;
let value = Math.max(
Math.abs(overviewData[path].max),
Math.abs(overviewData[path].min)
);
let negative = false;
let magnitude = 0;
@ -145,8 +167,6 @@ function Overview(props: OverviewProps) {
value /= 1000;
magnitude++;
}
console.log(path, magnitude);
overviewData[path].magnitude = prefixes[magnitude];
});
@ -175,8 +195,6 @@ function Overview(props: OverviewProps) {
path = '/Battery/Dc/Power';
chartData.dcPower = [{ name: 'Battery Power', data: data[path] }];
//console.log(overviewData[path]);
//console.log(data[path]);
chartOverview.dcPower = {
magnitude: overviewData[path].magnitude,
unit: '(' + overviewData[path].magnitude + 'W' + ')',
@ -218,37 +236,129 @@ function Overview(props: OverviewProps) {
chartData: chartData,
chartOverview: chartOverview
};
//return chartData;
};
useEffect(() => {
const subscription = cache.gotData
.pipe(
startWith(0),
throttleTime(200, undefined, { leading: true, trailing: true }),
withLatestFrom(times$)
)
.subscribe(([_, times]) => {
const timeSeries = cache.getSeries(times);
const left = cache.gotData.pipe(
startWith(UnixTime.fromTicks(0)),
throttleTime(200, undefined, { leading: true, trailing: true })
);
console.log(timeSeries);
const right = times$.pipe(
tap((times) => {
//console.log(times);
})
);
const result: {
chartData: chartDataInterface;
chartOverview: overviewInterface;
} = transformToGraphData(timeSeries);
const combined = combineLatest([left, right]);
setChartData(result.chartData);
setChartOverview(result.chartOverview);
});
const subscription = combined.subscribe(([_, times]) => {
const timeSeries = cache.getSeries(times);
const result: {
chartData: chartDataInterface;
chartOverview: overviewInterface;
} = transformToGraphData(timeSeries);
setChartData(result.chartData);
setChartOverview(result.chartOverview);
});
return () => subscription.unsubscribe();
}, []);
const handleBeforeZoom = (chartContext, { xaxis }) => {
const startX = parseInt(xaxis.min) / 1000;
const endX = parseInt(xaxis.max) / 1000;
const times = createTimes(
TimeRange.fromTimes(UnixTime.fromTicks(startX), UnixTime.fromTicks(endX)),
numOfPointsToFetch
);
cache.getSeries(times);
times$.next(times);
};
const handleDoubleClick = () => {
const times = createTimes(
UnixTime.now().rangeBefore(TimeSpan.fromDays(1)),
numOfPointsToFetch
);
cache.getSeries(times);
times$.next(times);
};
const handle24HourData = () => {
const times = createTimes(
UnixTime.now().rangeBefore(TimeSpan.fromDays(1)),
numOfPointsToFetch
);
cache.getSeries(times);
times$.next(times);
};
const handleWeekData = () => {
const times = createTimes(
UnixTime.now().rangeBefore(TimeSpan.fromWeeks(1)),
numOfPointsToFetch
);
cache.getSeries(times);
times$.next(times);
};
const handleMonthData = () => {
const times = createTimes(
UnixTime.now().rangeBefore(TimeSpan.fromWeeks(4)),
numOfPointsToFetch
);
cache.getSeries(times);
times$.next(times);
};
const renderGraphs = () => {
return (
<Container maxWidth="xl">
<Grid container>
<Grid item xs={12} md={12}>
<Button
variant="contained"
onClick={handle24HourData}
sx={{
marginTop: '20px',
backgroundColor: '#ffc04d',
color: '#000000',
'&:hover': { bgcolor: '#f7b34d' }
}}
>
<FormattedMessage id="24_hours" defaultMessage="24-hours" />
</Button>
<Button
variant="contained"
onClick={handleWeekData}
sx={{
marginTop: '20px',
marginLeft: '10px',
backgroundColor: '#ffc04d',
color: '#000000',
'&:hover': { bgcolor: '#f7b34d' }
}}
>
<FormattedMessage id="lastweek" defaultMessage="Last week" />
</Button>
<Button
variant="contained"
onClick={handleMonthData}
sx={{
marginTop: '20px',
marginLeft: '10px',
backgroundColor: '#ffc04d',
color: '#000000',
'&:hover': { bgcolor: '#f7b34d' }
}}
>
<FormattedMessage id="lastmonth" defaultMessage="Last Month" />
</Button>
</Grid>
<Grid item xs={12} md={12}>
<Grid
container
@ -273,7 +383,10 @@ function Overview(props: OverviewProps) {
<Box display="flex" alignItems="center">
<Box>
<Typography variant="subtitle1" noWrap>
Battery SOC (State Of Charge)
<FormattedMessage
id="battery_soc"
defaultMessage="Battery SOC (State Of Charge)"
/>
</Typography>
</Box>
</Box>
@ -287,7 +400,14 @@ function Overview(props: OverviewProps) {
></Box>
</Box>
<ReactApexChart
options={getChartOptions(chartOverview.soc)}
options={{
...getChartOptions(chartOverview.soc),
chart: {
events: {
beforeZoom: handleBeforeZoom
}
}
}}
series={chartData.soc}
type="area"
height={350}
@ -310,7 +430,10 @@ function Overview(props: OverviewProps) {
<Box display="flex" alignItems="center">
<Box>
<Typography variant="subtitle1" noWrap>
Battery Temperature
<FormattedMessage
id="battery_temperature"
defaultMessage="Battery Temperature"
/>
</Typography>
</Box>
</Box>
@ -323,12 +446,21 @@ function Overview(props: OverviewProps) {
}}
></Box>
</Box>
<ReactApexChart
options={getChartOptions(chartOverview.temperature)}
series={chartData.temperature}
type="line"
height={350}
/>
<div onDoubleClick={handleDoubleClick}>
<ReactApexChart
options={{
...getChartOptions(chartOverview.temperature),
chart: {
events: {
beforeZoom: handleBeforeZoom
}
}
}}
series={chartData.temperature}
type="area"
height={350}
/>
</div>
</Card>
</Grid>
</Grid>
@ -356,7 +488,10 @@ function Overview(props: OverviewProps) {
<Box display="flex" alignItems="center">
<Box>
<Typography variant="subtitle1" noWrap>
Battery Power
<FormattedMessage
id="pv_production"
defaultMessage="PV Production"
/>
</Typography>
</Box>
</Box>
@ -369,12 +504,21 @@ function Overview(props: OverviewProps) {
}}
></Box>
</Box>
<ReactApexChart
options={getChartOptions(chartOverview.dcPower)}
series={chartData.dcPower}
type="area"
height={350}
/>
<div onDoubleClick={handleDoubleClick}>
<ReactApexChart
options={{
...getChartOptions(chartOverview.pvProduction),
chart: {
events: {
beforeZoom: handleBeforeZoom
}
}
}}
series={chartData.pvProduction}
type="area"
height={350}
/>
</div>
</Card>
</Grid>
<Grid item md={6} xs={12}>
@ -393,7 +537,10 @@ function Overview(props: OverviewProps) {
<Box display="flex" alignItems="center">
<Box>
<Typography variant="subtitle1" noWrap>
Grid Power
<FormattedMessage
id="grid_power"
defaultMessage="Grid Power"
/>
</Typography>
</Box>
</Box>
@ -406,12 +553,21 @@ function Overview(props: OverviewProps) {
}}
></Box>
</Box>
<ReactApexChart
options={getChartOptions(chartOverview.gridPower)}
series={chartData.gridPower}
type="area"
height={350}
/>
<div onDoubleClick={handleDoubleClick}>
<ReactApexChart
options={{
...getChartOptions(chartOverview.gridPower),
chart: {
events: {
beforeZoom: handleBeforeZoom
}
}
}}
series={chartData.gridPower}
type="area"
height={350}
/>
</div>
</Card>
</Grid>
</Grid>
@ -438,7 +594,10 @@ function Overview(props: OverviewProps) {
<Box display="flex" alignItems="center">
<Box>
<Typography variant="subtitle1" noWrap>
PV Production
<FormattedMessage
id="battery_power"
defaultMessage="Battery Power"
/>
</Typography>
</Box>
</Box>
@ -451,12 +610,21 @@ function Overview(props: OverviewProps) {
}}
></Box>
</Box>
<ReactApexChart
options={getChartOptions(chartOverview.pvProduction)}
series={chartData.pvProduction}
type="area"
height={350}
/>
<div onDoubleClick={handleDoubleClick}>
<ReactApexChart
options={{
...getChartOptions(chartOverview.dcPower),
chart: {
events: {
beforeZoom: handleBeforeZoom
}
}
}}
series={chartData.dcPower}
type="area"
height={350}
/>
</div>
</Card>
</Grid>
<Grid item md={6} xs={12}>
@ -475,7 +643,10 @@ function Overview(props: OverviewProps) {
<Box display="flex" alignItems="center">
<Box>
<Typography variant="subtitle1" noWrap>
DC Bus Voltage
<FormattedMessage
id="dc_voltage"
defaultMessage="DC Bus Voltage"
/>
</Typography>
</Box>
</Box>
@ -488,12 +659,21 @@ function Overview(props: OverviewProps) {
}}
></Box>
</Box>
<ReactApexChart
options={getChartOptions(chartOverview.dcBusVoltage)}
series={chartData.dcBusVoltage}
type="line"
height={350}
/>
<div onDoubleClick={handleDoubleClick}>
<ReactApexChart
options={{
...getChartOptions(chartOverview.dcBusVoltage),
chart: {
events: {
beforeZoom: handleBeforeZoom
}
}
}}
series={chartData.dcBusVoltage}
type="area"
height={350}
/>
</div>
</Card>
</Grid>
</Grid>

View File

@ -23,6 +23,8 @@ function Topology(props: TopologyProps) {
setShowValues(!showValues);
};
const isMobile = window.innerWidth <= 1490;
return (
<Container maxWidth="xl" style={{ backgroundColor: 'white' }}>
<Grid container>
@ -56,7 +58,7 @@ function Topology(props: TopologyProps) {
xs={12}
md={12}
style={{
height: '600px',
height: isMobile ? '550px' : '600px',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
@ -66,7 +68,9 @@ function Topology(props: TopologyProps) {
<TopologyColumn
centerBox={{
title: 'Grid',
data: props.values.grid
data: props.values.grid,
connected:
props.values.gridBox.values[0].value.toString() != 'Disabled'
}}
centerConnection={{
orientation: 'horizontal',
@ -85,7 +89,10 @@ function Topology(props: TopologyProps) {
<TopologyColumn
topBox={{
title: 'Pv Inverter',
data: props.values.gridBusToPvOnGridbusConnection
data: props.values.gridBusToPvOnGridbusConnection,
connected:
props.values.pvOnAcGridBox.values[0].value.toString() !=
'Disabled'
}}
topConnection={{
orientation: 'vertical',
@ -101,22 +108,27 @@ function Topology(props: TopologyProps) {
}}
centerBox={{
title: 'Grid Bus',
data: props.values.gridBus
data: props.values.gridBus,
connected: true
}}
centerConnection={{
orientation: 'horizontal',
data: props.values.gridBusToIslandBusConnection,
amount: props.values.gridBusToIslandBusConnection
? getAmount(
highestConnectionValue,
props.values.gridBusToIslandBusConnection.values
)
: 0,
data: props.values.gridBusToIslandBusConnection,
showValues: showValues
}}
bottomBox={{
title: 'AC Loads',
data: props.values.gridBusToLoadOnGridBusConnection
data: props.values.gridBusToLoadOnGridBusConnection,
connected:
props.values.loadOnAcGridBox.values[0].value.toString() !=
'Disabled'
}}
bottomConnection={{
orientation: 'vertical',
@ -136,7 +148,10 @@ function Topology(props: TopologyProps) {
<TopologyColumn
topBox={{
title: 'Pv Inverter',
data: props.values.pvOnIslandBusToIslandBusConnection
data: props.values.pvOnIslandBusToIslandBusConnection,
connected:
props.values.pvOnIslandBusBox.values[0].value.toString() !=
'Disabled'
}}
topConnection={{
orientation: 'vertical',
@ -152,7 +167,8 @@ function Topology(props: TopologyProps) {
}}
centerBox={{
title: 'Island Bus',
data: props.values.islandBus
data: props.values.islandBus,
connected: true
}}
centerConnection={{
orientation: 'horizontal',
@ -167,7 +183,10 @@ function Topology(props: TopologyProps) {
}}
bottomBox={{
title: 'AC Loads',
data: props.values.islandBusToLoadOnIslandBusConnection
data: props.values.islandBusToLoadOnIslandBusConnection,
connected:
props.values.loadOnIslandBusBox.values[0].value.toString() !=
'Disabled'
}}
bottomConnection={{
orientation: 'vertical',
@ -187,7 +206,8 @@ function Topology(props: TopologyProps) {
<TopologyColumn
centerBox={{
title: 'AC-DC',
data: props.values.inverter
data: props.values.inverter,
connected: true
}}
centerConnection={{
orientation: 'horizontal',
@ -205,8 +225,10 @@ function Topology(props: TopologyProps) {
/>
<TopologyColumn
topBox={{
title: 'Pv DcDc',
data: props.values.pvOnDcBusToDcBusConnection
title: 'Pv DC-DC',
data: props.values.pvOnDcBusToDcBusConnection,
connected:
props.values.pvOnDcBox.values[0].value.toString() != 'Disabled'
}}
topConnection={{
orientation: 'vertical',
@ -222,7 +244,8 @@ function Topology(props: TopologyProps) {
}}
centerBox={{
title: 'DC Link',
data: props.values.dcBus
data: props.values.dcBus,
connected: true
}}
centerConnection={{
orientation: 'horizontal',
@ -237,7 +260,10 @@ function Topology(props: TopologyProps) {
}}
bottomBox={{
title: 'DC Loads',
data: props.values.dcBusToLoadOnDcConnection
data: props.values.dcBusToLoadOnDcConnection,
connected:
props.values.loadOnDcBox.values[0].value.toString() !=
'Disabled'
}}
bottomConnection={{
orientation: 'vertical',
@ -257,7 +283,8 @@ function Topology(props: TopologyProps) {
<TopologyColumn
centerBox={{
title: 'DC-DC',
data: props.values.dcDc
data: props.values.dcDc,
connected: true
}}
centerConnection={{
orientation: 'horizontal',
@ -276,7 +303,9 @@ function Topology(props: TopologyProps) {
<TopologyColumn
centerBox={{
title: 'Battery',
data: props.values.battery
data: props.values.battery,
connected:
props.values.batteryBox.values[0].value.toString() != 'Disabled'
}}
isLast={true}
isFirst={false}

View File

@ -5,6 +5,17 @@
border-bottom: none;
}
.isMobile.horizontalLine {
position: absolute;
overflow: hidden;
border-left: none;
margin-left: 142px;
border-right: none;
}
.horizontalLine {
position: absolute;
overflow: hidden;
@ -15,59 +26,60 @@
.dotRight {
position: absolute;
margin-left: 35px;
width: 3px;
height: 3px;
border-radius: 50%;
background-color: #f7b34d;
animation: rightflow 2s linear infinite;
transform: translateX(-39px); /* Initial position off-screen */
}
.dotLeft {
position: absolute;
margin-left: 35px;
width: 3px;
height: 3px;
border-radius: 50%;
background-color: #f7b34d;
animation: leftflow 2s linear infinite;
transform: translateX(-39px); /* Initial position off-screen */
}
.verticalDotDown {
position: absolute;
margin-top: 35px;
width: 3px;
height: 3px;
border-radius: 50%;
background-color: #f7b34d;
animation: verticalDownFlow 2s linear infinite;
transform: translateY(-39px);
}
@keyframes rightflow {
0% {
left: -35px;
transform: translateX(-35px);
}
100% {
left: 110%;
transform: translateX(1000%);
}
}
@keyframes leftflow {
0% {
left: 110px;
transform: translateX(1000%);
}
100% {
left: -35px;
transform: translateX(-35px);
}
}
@keyframes verticalDownFlow {
0% {
top: -35px;
transform: translateY(-35px);
}
100% {
top: 100%;
transform: translateY(1050%);
}
}

View File

@ -12,6 +12,7 @@ import BatteryCharging60Icon from '@mui/icons-material/BatteryCharging60';
import OutletIcon from '@mui/icons-material/Outlet';
import SolarPowerIcon from '@mui/icons-material/SolarPower';
import PowerInputIcon from '@mui/icons-material/PowerInput';
import SignalWifiConnectedNoInternet4Icon from '@mui/icons-material/SignalWifiConnectedNoInternet4';
import BoltIcon from '@mui/icons-material/Bolt';
import { BoxData } from '../Log/graph.util';
import inverterImage from 'src/Resources/images/inverter.png';
@ -21,6 +22,7 @@ import converterImage from 'src/Resources/images/converter.png';
export interface TopologyBoxProps {
title: string;
data?: BoxData;
connected?: boolean;
}
const isInt = (value: number) => {
@ -45,7 +47,7 @@ function formatPower(value) {
magnitude++;
}
const roundedValue = value.toFixed(2);
const roundedValue = value.toFixed(1);
return negative === false
? `${roundedValue} ${prefixes[magnitude]}`
@ -54,28 +56,32 @@ function formatPower(value) {
function TopologyBox(props: TopologyBoxProps) {
const theme = useTheme();
const isMobile = window.innerWidth <= 1490;
return (
<Card
sx={{
visibility:
props.data && props.data.values[0].value != 0 ? 'visible' : 'hidden',
width: '104px',
//props.data && props.data.values[0].value != 0 ? 'visible' : 'hidden',
props.connected ? 'visible' : 'hidden',
width: isMobile ? '90px' : '104px',
height:
props.title === 'Battery'
? '165px'
: props.title === 'AC Loads' ||
props.title === 'DC Loads' ||
props.title === 'Pv Inverter' ||
props.title === 'Pv DcDc'
props.title === 'Pv DC-DC'
? '100px'
: '150px',
backgroundColor:
props.title === 'Grid Bus' ||
props.title === 'Island Bus' ||
props.title === 'DC Link'
? '#f7b34d'
: 'none',
backgroundColor: !props.data
? 'darkgrey'
: props.title === 'Grid Bus' ||
props.title === 'Island Bus' ||
props.title === 'DC Link'
? '#f7b34d'
: 'none',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
@ -93,7 +99,7 @@ function TopologyBox(props: TopologyBoxProps) {
textAlign: 'center'
}}
>
{props.title === 'Battery' && (
{props.data && props.title === 'Battery' && (
<Typography variant="h5" noWrap>
{props.title} (x{props.data.values.length - 4})
</Typography>
@ -104,7 +110,20 @@ function TopologyBox(props: TopologyBoxProps) {
</Typography>
)}
{props.title === 'AC-DC' && (
{!props.data && (
<SignalWifiConnectedNoInternet4Icon
style={{
fontSize: 40,
color: 'black',
backgroundColor: 'darkgrey',
padding: '5px',
borderTopLeftRadius: '4px',
borderTopRightRadius: '4px'
}}
></SignalWifiConnectedNoInternet4Icon>
)}
{props.data && props.title === 'AC-DC' && (
<img
src={inverterImage}
style={{
@ -115,7 +134,7 @@ function TopologyBox(props: TopologyBoxProps) {
/>
)}
{props.title === 'DC Link' && (
{props.data && props.title === 'DC Link' && (
<PowerInputIcon
style={{
fontSize: 40,
@ -128,7 +147,7 @@ function TopologyBox(props: TopologyBoxProps) {
></PowerInputIcon>
)}
{props.title === 'DC-DC' && (
{props.data && props.title === 'DC-DC' && (
<img
src={converterImage}
style={{
@ -139,18 +158,20 @@ function TopologyBox(props: TopologyBoxProps) {
/>
)}
{(props.title === 'Grid Bus' || props.title === 'Island Bus') && (
<img
src={acCurrentImage}
style={{
width: '40px',
height: '40px',
backgroundColor: '#f7b34d'
}}
/>
)}
{props.data &&
(props.title === 'Grid Bus' || props.title === 'Island Bus') && (
<img
src={acCurrentImage}
style={{
width: '40px',
height: '40px',
backgroundColor: '#f7b34d'
}}
/>
)}
{props.title != 'AC-DC' &&
{props.data &&
props.title != 'AC-DC' &&
props.title != 'DC Link' &&
props.title != 'DC-DC' && (
<AvatarWrapper
@ -163,7 +184,7 @@ function TopologyBox(props: TopologyBoxProps) {
}}
>
{(props.title === 'Pv Inverter' ||
props.title === 'Pv DcDc') && (
props.title === 'Pv DC-DC') && (
<SolarPowerIcon
style={{
fontSize: 30,
@ -212,6 +233,7 @@ function TopologyBox(props: TopologyBoxProps) {
)}
{props.data && <Divider sx={{ width: '150%', marginTop: '0px' }} />}
{props.data && (
<Box
sx={{

View File

@ -16,6 +16,8 @@ interface TopologyColumnProps {
}
function TopologyColumn(props: TopologyColumnProps) {
const isMobile = window.innerWidth <= 1490;
return (
<Box
sx={{
@ -23,7 +25,7 @@ function TopologyColumn(props: TopologyColumnProps) {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
marginLeft: props.isFirst ? '0px' : '68px'
marginLeft: props.isFirst ? '0px' : isMobile ? '52px' : '68px'
}}
>
<TopologyBox {...props.topBox}></TopologyBox>

View File

@ -45,7 +45,7 @@ function formatPower(value) {
magnitude++;
}
const roundedValue = value.toFixed(2);
const roundedValue = value.toFixed(1);
return negative === false
? `${roundedValue} ${prefixes[magnitude]}`
@ -61,12 +61,14 @@ function TopologyFlow(props: TopologyFlowProps) {
{ animationDelay: string; left: string }[]
>([]);
const numOfDots = 400;
const minNumberOfDots = 100;
const numOfDots = 200;
const minNumberOfDots = 50;
const minHeight = 2;
const maxHeight = 70;
const minWidth = 2;
const maxWidth = 68;
const maxWidthMobile = 50;
const isMobile = window.innerWidth <= 1490;
const desiredNumOfDots =
numOfDots * props.amount < minNumberOfDots
@ -83,7 +85,7 @@ function TopologyFlow(props: TopologyFlowProps) {
setDotStyleVertical(
Array.from({ length: desiredNumOfDots }, () => getRandomStyleVertical())
);
}, []);
}, [desiredNumOfDots]);
return (
<>
@ -91,7 +93,7 @@ function TopologyFlow(props: TopologyFlowProps) {
<Box
sx={{
position: 'absolute',
marginLeft: '170px',
marginLeft: isMobile ? '142px' : '170px',
marginTop: '2px',
backgroundColor: 'transparent',
display: 'flex',
@ -103,6 +105,7 @@ function TopologyFlow(props: TopologyFlowProps) {
{props.showValues && props.data.values[0].value != 0 && (
<Typography
sx={{
marginTop: '1px',
color: 'black',
bgcolor: 'background.paper',
borderRadius: 5,
@ -116,16 +119,16 @@ function TopologyFlow(props: TopologyFlowProps) {
)}
</Box>
)}
<div
className={props.orientation === 'vertical' ? 'line' : 'horizontalLine'}
className={`${
props.orientation === 'vertical' ? 'line' : 'horizontalLine'
} ${isMobile ? 'isMobile' : ''}`}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position:
props.orientation === 'horizontal' ? 'absolute' : 'relative',
height:
props.orientation === 'horizontal'
? `${Math.min(
@ -133,13 +136,14 @@ function TopologyFlow(props: TopologyFlowProps) {
maxHeight
)}px`
: `${maxHeight}px`,
width:
props.orientation === 'vertical'
? `${Math.min(
Math.max(props.amount * maxWidth, minWidth),
maxWidth
)}px`
: isMobile
? `${maxWidthMobile}px`
: `${maxWidth}px`
}}
>

View File

@ -110,7 +110,7 @@ function CustomTreeItem(props: CustomTreeItemProps) {
height: '23px',
color: 'red',
borderRadius: '50%',
marginLeft: '21px',
marginLeft: '30px',
marginTop: '30px'
}}
/>
@ -123,7 +123,7 @@ function CustomTreeItem(props: CustomTreeItemProps) {
size={20}
sx={{
color: '#f7b34d',
marginLeft: '20px',
marginLeft: '22px',
marginTop: '30px'
}}
/>
@ -136,7 +136,7 @@ function CustomTreeItem(props: CustomTreeItemProps) {
width: '20px',
height: '20px',
borderRadius: '50%',
marginLeft: '20px',
marginLeft: '17px',
backgroundColor:
status === 2
? 'red'

View File

@ -8,9 +8,11 @@ import {
Container,
Grid,
IconButton,
Modal,
Tab,
Tabs,
TextField,
Typography,
useTheme
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material';
@ -46,6 +48,7 @@ function Folder(props: singleFolderProps) {
const selectedBulkActions = selectedUser !== -1;
const searchParams = new URLSearchParams(location.search);
const folderId = parseInt(searchParams.get('folder'));
const [openModalDeleteFolder, setOpenModalDeleteFolder] = useState(false);
const installationContext = useContext(InstallationsContext);
const {
@ -126,7 +129,18 @@ function Folder(props: singleFolderProps) {
const handleDeleteFolder = (e) => {
setLoading(true);
setError(false);
setOpenModalDeleteFolder(true);
};
const deleteFolderModalHandle = (e) => {
setOpenModalDeleteFolder(false);
deleteFolder(formValues);
setLoading(false);
};
const deleteFolderModalHandleCancel = (e) => {
setOpenModalDeleteFolder(false);
setLoading(false);
};
const handleFolderFormSubmit = () => {
@ -155,6 +169,80 @@ function Folder(props: singleFolderProps) {
if (folderId == props.current_folder.id) {
return (
<>
{openModalDeleteFolder && (
<Modal
open={openModalDeleteFolder}
onClose={() => setOpenModalDeleteFolder(false)}
aria-labelledby="error-modal"
aria-describedby="error-modal-description"
>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 350,
bgcolor: 'background.paper',
borderRadius: 4,
boxShadow: 24,
p: 4,
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}}
>
<Typography
variant="body1"
gutterBottom
sx={{ fontWeight: 'bold' }}
>
Do you want to delete this folder?
</Typography>
<Typography
variant="body1"
gutterBottom
sx={{ fontSize: '0.875rem' }}
>
All installations of this folder will be deleted.
</Typography>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: 10
}}
>
<Button
sx={{
marginTop: 2,
textTransform: 'none',
bgcolor: '#ffc04d',
color: '#111111',
'&:hover': { bgcolor: '#f7b34d' }
}}
onClick={deleteFolderModalHandle}
>
Delete
</Button>
<Button
sx={{
marginTop: 2,
marginLeft: 2,
textTransform: 'none',
bgcolor: '#ffc04d',
color: '#111111',
'&:hover': { bgcolor: '#f7b34d' }
}}
onClick={deleteFolderModalHandleCancel}
>
Cancel
</Button>
</div>
</Box>
</Modal>
)}
{openModalFolder && (
<FolderForm
cancel={handleFormCancel}
@ -169,7 +257,7 @@ function Folder(props: singleFolderProps) {
parentid={props.current_folder.id}
/>
)}
<Grid item xs={12} md={9}>
<Grid item xs={12} md={12}>
<TabsContainerWrapper>
<Tabs
onChange={handleTabsChange}
@ -253,30 +341,14 @@ function Folder(props: singleFolderProps) {
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleFolderInformationUpdate}
sx={{
marginLeft: '10px'
}}
disabled={!areRequiredFieldsFilled()}
>
<FormattedMessage
id="applyChanges"
defaultMessage="Apply Changes"
/>
</Button>
)}
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleNewInstallationInsertion}
onClick={handleDeleteFolder}
sx={{
marginLeft: '10px'
}}
>
<FormattedMessage
id="addNewInstallation"
defaultMessage="Add new installation"
id="deleteFolder"
defaultMessage="Delete Folder"
/>
</Button>
)}
@ -299,14 +371,30 @@ function Folder(props: singleFolderProps) {
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleDeleteFolder}
onClick={handleNewInstallationInsertion}
sx={{
marginLeft: '10px'
}}
>
<FormattedMessage
id="deleteFolder"
defaultMessage="Delete Folder"
id="addNewInstallation"
defaultMessage="Add new installation"
/>
</Button>
)}
{currentUser.hasWriteAccess && (
<Button
variant="contained"
onClick={handleFolderInformationUpdate}
sx={{
marginLeft: '10px'
}}
disabled={!areRequiredFieldsFilled()}
>
<FormattedMessage
id="applyChanges"
defaultMessage="Apply Changes"
/>
</Button>
)}

View File

@ -7,7 +7,6 @@ import CustomTreeItem from './CustomTreeItem';
import Installation from '../Installations/Installation';
import Folder from './Folder';
import { InstallationsContext } from 'src/contexts/InstallationsContextProvider';
import LogContextProvider from 'src/contexts/LogContextProvider';
function InstallationTree() {
const { foldersAndInstallations, fetchAllFoldersAndInstallations } =
@ -47,46 +46,44 @@ function InstallationTree() {
};
return (
<LogContextProvider>
<Grid container spacing={1} sx={{ marginTop: 0.1 }}>
<Grid item xs={12} md={3}>
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
defaultExpanded={['1Folder']}
>
{foldersAndInstallations.map((node, index) => {
return (
<TreeNode
key={node.id.toString() + node.type}
node={node}
parent_id={'0'}
/>
);
})}
</TreeView>
</Grid>
{foldersAndInstallations.map((installation) => {
if (installation.type == 'Installation') {
<Grid container spacing={1} sx={{ marginTop: 0.1 }}>
<Grid item xs={12} md={12}>
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
defaultExpanded={['1Folder']}
>
{foldersAndInstallations.map((node, index) => {
return (
<Installation
key={installation.id + installation.type}
current_installation={installation}
type="tree"
></Installation>
<TreeNode
key={node.id.toString() + node.type}
node={node}
parent_id={'0'}
/>
);
} else {
return (
<Folder
key={installation.id + installation.type}
current_folder={installation}
></Folder>
);
}
})}
})}
</TreeView>
</Grid>
</LogContextProvider>
{foldersAndInstallations.map((installation) => {
if (installation.type == 'Installation') {
return (
<Installation
key={installation.id + installation.type}
current_installation={installation}
type="tree"
></Installation>
);
} else {
return (
<Folder
key={installation.id + installation.type}
current_folder={installation}
></Folder>
);
}
})}
</Grid>
);
}

View File

@ -55,6 +55,8 @@ function folderForm(props: folderFormProps) {
props.cancel();
};
const isMobile = window.innerWidth <= 1490;
const areRequiredFieldsFilled = () => {
for (const field of requiredFields) {
if (!formValues[field]) {
@ -75,7 +77,7 @@ function folderForm(props: folderFormProps) {
<Box
sx={{
position: 'absolute',
top: '30%',
top: isMobile ? '50%' : '30%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 600,

View File

@ -1,6 +1,7 @@
import { Box, Grid, useTheme } from '@mui/material';
import InstallationTree from './InstallationTree';
import InstallationsContextProvider from 'src/contexts/InstallationsContextProvider';
import LogContextProvider from '../../../contexts/LogContextProvider';
function TreeView() {
const theme = useTheme();
@ -9,7 +10,9 @@ function TreeView() {
<InstallationsContextProvider>
<Grid item xs={12}>
<Box p={4}>
<InstallationTree />
<LogContextProvider>
<InstallationTree />
</LogContextProvider>
</Box>
</Grid>
</InstallationsContextProvider>

View File

@ -14,6 +14,7 @@ import {
} from '@mui/material';
import { InnovEnergyUser } from 'src/interfaces/UserTypes';
import User from './User';
import { useNavigate } from 'react-router-dom';
interface FlatUsersViewProps {
users: InnovEnergyUser[];
@ -23,10 +24,14 @@ interface FlatUsersViewProps {
const FlatUsersView = (props: FlatUsersViewProps) => {
const [selectedUser, setSelectedUser] = useState<number>(-1);
const selectedBulkActions = selectedUser !== -1;
const navigate = useNavigate();
const handleSelectOneUser = (installationID: number): void => {
if (selectedUser != installationID) {
setSelectedUser(installationID);
// navigate(routes.users + '?user=' + installationID.toString(), {
// replace: true
// });
} else {
setSelectedUser(-1);
}
@ -46,12 +51,14 @@ const FlatUsersView = (props: FlatUsersViewProps) => {
return props.users.find((user) => user.id === id);
};
const isMobile = window.innerWidth <= 1490;
return (
<Grid container spacing={1} sx={{ marginTop: '1px' }}>
<Grid item xs={12} md={3}>
<Grid item xs={12} md={isMobile ? 5 : 4}>
<Card>
<Divider />
<TableContainer>
<TableContainer sx={{ maxHeight: '520px', overflowY: 'auto' }}>
<Table>
<TableHead>
<TableRow>
@ -67,7 +74,7 @@ const FlatUsersView = (props: FlatUsersViewProps) => {
isRowHovered === user.id
? {
cursor: 'pointer',
backgroundColor: theme.colors.primary.lighter // Set your desired hover background color here
backgroundColor: theme.colors.primary.lighter
}
: {};
@ -113,7 +120,7 @@ const FlatUsersView = (props: FlatUsersViewProps) => {
</Card>
</Grid>
{selectedBulkActions && (
{selectedUser && (
<User
current_user={findUser(selectedUser)}
fetchDataAgain={props.fetchDataAgain}

View File

@ -8,9 +8,11 @@ import {
Container,
Grid,
IconButton,
Modal,
Tab,
Tabs,
TextField,
Typography,
useTheme
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material'; // Import CloseIcon
@ -19,6 +21,7 @@ import axiosConfig from 'src/Resources/axiosConfig';
import { InnovEnergyUser } from 'src/interfaces/UserTypes';
import { TokenContext } from 'src/contexts/tokenContext';
import { TabsContainerWrapper } from 'src/layouts/TabsContainerWrapper';
import { FormattedMessage } from 'react-intl';
interface singleUserProps {
current_user: InnovEnergyUser;
@ -34,6 +37,8 @@ function User(props: singleUserProps) {
const [formValues, setFormValues] = useState(props.current_user);
const tokencontext = useContext(TokenContext);
const { removeToken } = tokencontext;
const tabs = [{ value: 'user', label: 'User' }];
const [openModalDeleteFolder, setOpenModalDeleteFolder] = useState(false);
useEffect(() => {
setFormValues(props.current_user);
@ -43,8 +48,6 @@ function User(props: singleUserProps) {
return null;
}
const tabs = [{ value: 'user', label: 'User' }];
const handleTabsChange = (_event: ChangeEvent<{}>, value: string): void => {
setCurrentTab(value);
setError(false);
@ -60,32 +63,21 @@ function User(props: singleUserProps) {
const handleSubmit = (e) => {
setLoading(true);
setError(false);
axiosConfig
.put('/UpdateUser', formValues)
.then((response) => {
if (response) {
props.fetchDataAgain();
setLoading(false);
setUpdated(true);
setTimeout(() => {
setUpdated(false);
}, 3000);
}
})
.catch((error) => {
setLoading(false);
setError(true);
if (error.response && error.response.status == 401) {
removeToken();
}
});
};
const handleDelete = (e) => {
setLoading(true);
setError(false);
setOpenModalDeleteFolder(true);
};
const deleteUserModalHandleCancel = (e) => {
setLoading(false);
setError(false);
setOpenModalDeleteFolder(false);
};
const deleteUserModalHandle = (e) => {
axiosConfig
.delete(`/DeleteUser?userId=${formValues.id}`)
.then((response) => {
@ -102,15 +94,86 @@ function User(props: singleUserProps) {
.catch((error) => {
setLoading(false);
setError(true);
setOpenModalDeleteFolder(false);
if (error.response && error.response.status == 401) {
removeToken();
}
});
};
const isMobile = window.innerWidth <= 1490;
return (
<>
<Grid item xs={12} md={9}>
{openModalDeleteFolder && (
<Modal
open={openModalDeleteFolder}
onClose={() => setOpenModalDeleteFolder(false)}
aria-labelledby="error-modal"
aria-describedby="error-modal-description"
>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 350,
bgcolor: 'background.paper',
borderRadius: 4,
boxShadow: 24,
p: 4,
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}}
>
<Typography
variant="body1"
gutterBottom
sx={{ fontWeight: 'bold' }}
>
Do you want to delete this user?
</Typography>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: 10
}}
>
<Button
sx={{
marginTop: 2,
textTransform: 'none',
bgcolor: '#ffc04d',
color: '#111111',
'&:hover': { bgcolor: '#f7b34d' }
}}
onClick={deleteUserModalHandle}
>
Delete
</Button>
<Button
sx={{
marginTop: 2,
marginLeft: 2,
textTransform: 'none',
bgcolor: '#ffc04d',
color: '#111111',
'&:hover': { bgcolor: '#f7b34d' }
}}
onClick={deleteUserModalHandleCancel}
>
Cancel
</Button>
</div>
</Box>
</Modal>
)}
<Grid item xs={12} md={isMobile ? 7 : 8}>
<TabsContainerWrapper>
<Tabs
onChange={handleTabsChange}
@ -195,7 +258,10 @@ function User(props: singleUserProps) {
marginLeft: '10px'
}}
>
Apply Changes
<FormattedMessage
id="apply_changes"
defaultMessage="Apply Changes"
/>
</Button>
<Button
variant="contained"
@ -204,7 +270,10 @@ function User(props: singleUserProps) {
marginLeft: '10px'
}}
>
Delete User
<FormattedMessage
id="delete_user"
defaultMessage="Delete User"
/>
</Button>
{loading && (

View File

@ -50,6 +50,8 @@ function UsersSearch() {
setOpenModal(false);
};
const isMobile = window.innerWidth <= 1490;
return (
<>
<Grid container spacing={1}>
@ -65,7 +67,7 @@ function UsersSearch() {
<UserForm cancel={handleUserFormCancel} submit={handleUserFormSubmit} />
)}
<Grid container spacing={1} sx={{ marginTop: '1px' }}>
<Grid item xs={12} md={3}>
<Grid item xs={12} md={isMobile ? 5 : 3}>
<FormControl variant="outlined" fullWidth>
<TextField
placeholder="Search"

View File

@ -2,6 +2,7 @@ import Footer from 'src/components/Footer';
import { Box, Container, Grid, useTheme } from '@mui/material';
import UsersSearch from './UsersSearch';
import UsersContextProvider from 'src/contexts/UsersContextProvider';
import React from 'react';
function Users() {
const theme = useTheme();

View File

@ -103,6 +103,8 @@ function userForm(props: userFormProps) {
setSelectedInstallationNames(event.target.value);
};
const isMobile = window.innerWidth <= 1490;
const handleSubmit = async (e) => {
const res = await axiosConfig.post('/CreateUser', {
...formValues,
@ -189,10 +191,10 @@ function userForm(props: userFormProps) {
<Box
sx={{
position: 'absolute',
top: '30%',
top: isMobile ? '50%' : '30%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 600,
width: 500,
bgcolor: 'background.paper',
borderRadius: 4,
boxShadow: 24,

View File

@ -1,4 +1,4 @@
import { AxiosError } from 'axios';
import { AxiosError, AxiosResponse } from 'axios';
import {
createContext,
ReactNode,
@ -54,7 +54,7 @@ const InstallationsContextProvider = ({
}: {
children: ReactNode;
}) => {
const [installations, setInstallations] = useState([]);
const [installations, setInstallations] = useState<I_Installation[]>([]);
const [foldersAndInstallations, setFoldersAndInstallations] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
@ -67,7 +67,7 @@ const InstallationsContextProvider = ({
let isMounted = true;
axiosConfig
.get('/GetAllInstallations', {})
.then((res) => {
.then((res: AxiosResponse<I_Installation[]>) => {
setInstallations(res.data);
})
.catch((err: AxiosError) => {

View File

@ -16,9 +16,9 @@ export const LogContextProvider = ({ children }: { children: ReactNode }) => {
>({});
const BUFFER_LENGTH = 5;
const handleLogWarningOrError = (installation_id: number, value: number) => {
setInstallationStatus((prevStatus) => {
// Create a new object by spreading the previous state
const newStatus = { ...prevStatus };
if (!newStatus.hasOwnProperty(installation_id)) {
@ -29,6 +29,7 @@ export const LogContextProvider = ({ children }: { children: ReactNode }) => {
0,
BUFFER_LENGTH
);
return newStatus;
});
};
@ -39,9 +40,19 @@ export const LogContextProvider = ({ children }: { children: ReactNode }) => {
if (!installationStatus.hasOwnProperty(installationId)) {
status = -2;
} else {
if (installationId === 2) {
console.log(installationStatus[2]);
let i = 0;
//If at least one status value shows an error, then show error
for (i; i < installationStatus[installationId].length; i++) {
if (installationStatus[installationId][i] === 2) {
status = 2;
return status;
}
if (installationStatus[installationId][i] === 1) {
status = 1;
return status;
}
}
if (installationStatus[installationId][0] == -1) {
let i = 0;
for (i; i < installationStatus[installationId].length; i++) {
@ -49,7 +60,6 @@ export const LogContextProvider = ({ children }: { children: ReactNode }) => {
break;
}
}
if (i === installationStatus[installationId].length) {
status = -1;
}
@ -57,7 +67,6 @@ export const LogContextProvider = ({ children }: { children: ReactNode }) => {
status = installationStatus[installationId][0];
}
}
return status;
};

View File

@ -1,9 +1,5 @@
import {createContext, ReactNode, useState} from 'react';
//const setUser=(currentUser: InnovEnergyUser)=>{
// localStorage.setItem("currentUser",JSON.stringify(currentUser));
//}
// Define the shape of the context
interface TokenContextType {
token?: string | null;
@ -18,6 +14,8 @@ export const TokenContext = createContext<TokenContextType | undefined>(
// Create a UserContextProvider component
export const TokenContextProvider = ({ children }: { children: ReactNode }) => {
const searchParams = new URLSearchParams(location.search);
const tokenId = parseInt(searchParams.get('authToken'));
//Initialize context state with a "null" user
const [token, setToken] = useState(localStorage.getItem('token'));

View File

@ -265,6 +265,7 @@ export class TimeRange {
for (let t = this.from; t < this.to; t += period.ticks)
samples.push(UnixTime.fromTicks(t));
samples.push(UnixTime.fromTicks(this.to));
return samples;
}

View File

@ -9,7 +9,8 @@ export interface I_Installation extends I_S3Credentials {
location: string;
region: string;
country: string;
orderNumbers: string;
installationName: string;
orderNumbers: string[] | string;
lat: number;
long: number;
id: number;

View File

@ -2,12 +2,12 @@
"information": "Information",
"addNewChild": "Neues Kind hinzufügen",
"addNewDialogButton": "Neue Dialogschaltfläche hinzufügen",
"addUser": "Nutzer erstellen",
"addUser": "Neuen Benutzer erstellen",
"alarms": "Alarme",
"applyChanges": "Änderungen speichern",
"country": "Land",
"createNewFolder": "Neuen Ordner erstellen",
"createNewUser": "Neuen Nutzer erstellen",
"createNewFolder": "Neuer Ordner",
"createNewUser": "Neuer Benutzer",
"customerName": "Kundenname",
"email": "Email",
"english": "Englisch",
@ -16,27 +16,50 @@
"german": "Deutsch",
"groupTabs": "Gruppen",
"groupTree": "Gruppenbaum",
"overview": "Überblick",
"manage": "Zugriffsverwaltung",
"configuration": "Aufbau",
"installation_name_simple": "Installationsname: ",
"language": "Sprache",
"minimum_soc": "Minimum SoC",
"calibration_charge_forced": "Kalibrierungsladung erzwungen",
"grid_set_point": "Sollwert Netzleistung",
"Installed_Power_DC1010": "Installierte Leistung DC1010 TODO",
"Maximum_Discharge_Power": "Maximale Entladeleistung",
"Number_of_Batteries": "Anzahl der Batterien",
"24_hours": "24 Stunden",
"lastweek": "Letzte Woche",
"lastmonth": "Vergangener Monat",
"apply_changes": "Änderungen übernehmen",
"delete_user": "Benutzer löschen",
"battery_temperature": "Batterietemperatur",
"pv_production": "Photovoltaik Produktion",
"grid_power": "Netzstrom",
"battery_power": "Batterieleistung",
"dc_voltage": "DC-Busspannung",
"battery_soc": "Ladezustand (SOC)",
"installation_name": "Installationsname",
"inheritedAccess": "Vererbter Zugriff von",
"installation": "Installation",
"installationTabs": "Installationen",
"installations": "Installationen",
"lastWeek": "Letzte Woche",
"location": "Standort",
"log": "Logbuch",
"log": "Log daten",
"logout": "Abmelden",
"makeASelection": "Bitte wählen Sie links eine Auswahl",
"manageAccess": "Zugriff verwalten",
"manageAccess": "Zugriffsverwaltung",
"move": "Verschieben",
"moveTo": "Verschieben zu",
"moveTo": "Verschieben nach",
"moveTree": "Baum verschieben",
"name": "Name",
"navigationTabs": "Navigation",
"orderNumbers": "Bestellnummer",
"orderNumbers": "Bestellnummern",
"region": "Region",
"requiredLocation": "Standort ist erforderlich",
"requiredName": "Name ist erforderlich",
"requiredRegion": "Region ist erforderlich",
"search": "Suche",
"search": "Suchen",
"submit": "Senden",
"updateFolderErrorMessage": "Fehler, Ordner kann nicht aktualisiert werden",
"updatedSuccessfully": "Erfolgreich aktualisiert",
@ -44,27 +67,27 @@
"userTabs": "Nutzer",
"users": "Nutzer",
"status": "Status",
"live": "Live Übertragung",
"live": "Live Daten",
"deleteInstallation": "Installation löschen",
"errorOccured": "Ein Fehler ist aufgetreten",
"successfullyUpdated": "Erfolgreich aktualisiert",
"grantAccess": "Zugriff gewähren",
"UserswithDirectAccess": "Benutzer mit direktem Zugriff",
"UserswithInheritedAccess": "Benutzer mit geerbtem Zugriff",
"noerrors": "Es liegen keine Fehler vor",
"nowarnings": "Es gibt keine Warnungen",
"noUsersWithDirectAccessToThis": "Keine Benutzer mit direktem Zugriff darauf ",
"selectUsers": "Wählen Sie Benutzer aus",
"cancel": "Stornieren",
"UserswithInheritedAccess": "Benutzer mit vererbtem Zugriff",
"noerrors": "Keine Fehler",
"nowarnings": "Keine Warnungen",
"noUsersWithDirectAccessToThis": "Keine Benutzer mit direktem Zugriff",
"selectUsers": "Benutzer auswählen",
"cancel": "Abbrechen",
"addNewFolder": "Neuen Ordner hinzufügen",
"addNewInstallation": "Neue Installation hinzufügen",
"deleteFolder": "Lösche Ordner",
"grantAccessToFolders": "Gewähren Sie Zugriff auf Ordner",
"grantAccessToInstallations": "Gewähren Sie Zugriff auf Installationen",
"cannotloadloggingdata": "Protokollierungsdaten können nicht geladen werden",
"grantedAccessToUsers": "Benutzern Zugriff gewährt: ",
"unableToGrantAccess": "Der Zugriff auf kann nicht gewährt werden: ",
"deleteFolder": "Ordner löschen",
"grantAccessToFolders": "Zugriff auf Ordner gewähren",
"grantAccessToInstallations": "Zugriff auf Installationen gewähren",
"cannotloadloggingdata": "Log Daten können nicht geladen werden",
"grantedAccessToUsers": "Den Benutzern wurde den Zugriff gewährt",
"unableToGrantAccess": "Der Zugriff kann nicht gewährt werden",
"unableToLoadData": "Daten können nicht geladen werden",
"unableToRevokeAccess": "Der Zugriff kann nicht widerrufen werden",
"revokedAccessFromUser": "Zugriff vom Benutzer widerrufen: "
}
"unableToRevokeAccess": "Der Zugriff konnte nicht widerrufen werden",
"revokedAccessFromUser": "Zugriff vom Benutzer widerrufen"
}

View File

@ -1,42 +1,59 @@
{
"information": "Informations",
"addNewChild": "Ajouter un nouvel enfant",
"addNewDialogButton": "Ajouter un nouveau bouton de dialogue",
"information": "Information",
"addUser": "Créer un utilisateur",
"alarms": "Alarmes",
"applyChanges": "Appliquer les modifications",
"applyChanges": "Appliquer",
"country": "Pays",
"createNewFolder": "Créer un nouveau dossier",
"createNewUser": "Créer un nouvel utilisateur",
"createNewFolder": "Nouveau dossier",
"createNewUser": "Nouvel utilisateur",
"customerName": "Nom du client",
"email": "E-mail",
"email": "Courriel",
"english": "Anglais",
"error": "Erreur",
"folder": "Dossier",
"german": "Allemand",
"groupTabs": "Onglets de groupe",
"groupTree": "Arbre de groupe",
"overview": "Aperçu",
"manage": "Gestion des accès",
"configuration": "Configuration",
"installation_name": "Nom de l'installation",
"apply_changes": "Appliquer",
"delete_user": "Supprimer l'utilisateur",
"installation_name_simple": "Nom de l'installation: ",
"language": "Langue",
"minimum_soc": "Soc minimum",
"calibration_charge_forced": "Charge d'étalonnage forcée",
"grid_set_point": "Point de consigne de grid",
"Installed_Power_DC1010": "Alimentation branchée",
"Maximum_Discharge_Power": "Puissance de décharge maximale",
"Number_of_Batteries": "Nombre de batteries",
"24_hours": "24-heures",
"lastweek": "Semaine dernière",
"lastmonth": "Mois dernier",
"battery_temperature": "Température de la batterie",
"pv_production": "Production photovoltaïque",
"grid_power": "Alimentation du réseau",
"battery_power": "Puissance de la batterie",
"dc_voltage": "Tension du bus CC",
"battery_soc": "État de charge de la batterie",
"inheritedAccess": "Accès hérité de",
"installation": "Installation",
"installationTabs": "Onglets d'installation",
"installations": "Installations",
"lastWeek": "La semaine dernière",
"location": "Localisation",
"location": "Locali",
"log": "Journal",
"logout": "Déconnexion",
"logout": "Fermer las session",
"makeASelection": "Veuillez faire une sélection à gauche",
"manageAccess": "Gérer l'accès",
"move": "Déplacer",
"moveTo": "Déplacer à",
"moveTree": "Déplacer l'arbre",
"name": "Nom",
"navigationTabs": "Onglets de navigation",
"orderNumbers": "Numéro de commande",
"orderNumbers": "Numéros de commande",
"region": "Région",
"requiredLocation": "L'emplacement est requis",
"requiredLocation": "La localité est requis",
"requiredName": "Le nom est obligatoire",
"requiredRegion": "La région est obligatoire",
"search": "Recherche",
"search": "Rechercher",
"submit": "Soumettre",
"updateFolderErrorMessage": "Une erreur s'est produite, impossible de mettre à jour le dossier.",
"updatedSuccessfully": "Mise à jour réussie",
@ -46,14 +63,14 @@
"status": "Statut",
"live": "Diffusion en direct",
"deleteInstallation": "Supprimer l'installation",
"errorOccured": "Une erreur est survenue",
"errorOccured": "Une erreur sest produite",
"successfullyUpdated": "Mise à jour réussie",
"grantAccess": "Accorder l'accès",
"UserswithDirectAccess": "Utilisateurs avec accès direct",
"UserswithInheritedAccess": "Utilisateurs avec accès hérité",
"noerrors": "Il n'y a pas d'erreurs",
"nowarnings": "Il n'y a aucun avertissement",
"noUsersWithDirectAccessToThis": "Aucun utilisateur ayant un accès direct à ceci ",
"noUsersWithDirectAccessToThis": "Aucun utilisateur ayant un accès direct",
"selectUsers": "Sélectionnez les utilisateurs",
"cancel": "Annuler",
"addNewFolder": "Ajouter un nouveau dossier",
@ -62,9 +79,9 @@
"grantAccessToFolders": "Accorder l'accès aux dossiers",
"grantAccessToInstallations": "Accorder l'accès aux installations",
"cannotloadloggingdata": "Impossible de charger les données de journalisation",
"grantedAccessToUsers": "Accès accordé aux utilisateurs: ",
"unableToGrantAccess": "Impossible d'accorder l'accès à: ",
"grantedAccessToUsers": "Accès accordé aux utilisateurs",
"unableToGrantAccess": "Impossible d'accorder l'accès à",
"unableToLoadData": "Impossible de charger les données",
"unableToRevokeAccess": "Impossible de révoquer l'accès",
"revokedAccessFromUser": "Accès révoqué de l'utilisateur: "
}
"revokedAccessFromUser": "Accès révoqué de l'utilisateur"
}

View File

@ -6,10 +6,11 @@ import {
Menu,
MenuItem
} from '@mui/material';
import { useContext, useRef, useState } from 'react';
import React, { useContext, useRef, useState } from 'react';
import { styled } from '@mui/material/styles';
import ExpandMoreTwoToneIcon from '@mui/icons-material/ExpandMoreTwoTone';
import { ThemeContext } from '../../../../theme/ThemeProvider';
import { FormattedMessage } from 'react-intl';
interface HeaderButtonsProps {
language: string;
@ -102,20 +103,18 @@ function HeaderMenu(props: HeaderButtonsProps) {
handleClose();
};
const isMobile = window.innerWidth <= 1280;
return (
<>
<ListWrapper
sx={{
display: {
xs: 'none',
md: 'block'
}
color: isMobile ? 'white' : ''
}}
>
<List disablePadding component={Box} display="flex">
<ListItem
classes={{ root: 'MuiListItem-indicators' }}
button
ref={ref}
onClick={handleOpen}
>
@ -123,7 +122,7 @@ function HeaderMenu(props: HeaderButtonsProps) {
primaryTypographyProps={{ noWrap: true }}
primary={
<Box display="flex" alignItems="center">
Language
<FormattedMessage id="language" defaultMessage="Language" />
<Box display="flex" alignItems="center" pl={0.3}>
<ExpandMoreTwoToneIcon fontSize="small" />
</Box>

View File

@ -17,6 +17,7 @@ import axiosConfig from 'src/Resources/axiosConfig';
import { FormattedMessage } from 'react-intl';
import { TokenContext } from 'src/contexts/tokenContext';
import { useNavigate } from 'react-router-dom';
import routes from 'src/Resources/routes.json';
const UserBoxButton = styled(Button)(
({ theme }) => `
@ -68,7 +69,7 @@ function HeaderUserbox() {
removeToken();
removeUser();
localStorage.removeItem('theme');
navigate('/');
navigate(routes.login);
});
};

View File

@ -3,6 +3,7 @@ import { useContext } from 'react';
import {
alpha,
Box,
darken,
Divider,
IconButton,
lighten,
@ -44,12 +45,17 @@ interface HeaderProps {
function Header(props: HeaderProps) {
const { sidebarToggle, toggleSidebar } = useContext(SidebarContext);
const theme = useTheme();
const isMobile = window.innerWidth <= 1280;
return (
<HeaderWrapper
display="flex"
alignItems="center"
sx={{
backgroundColor: isMobile
? darken(theme.colors.alpha.black[100], 0.5)
: '',
boxShadow:
theme.palette.mode === 'dark'
? `0 1px 0 ${alpha(
@ -65,6 +71,23 @@ function Header(props: HeaderProps) {
)}`
}}
>
<Box
component="span"
sx={{
ml: 2,
display: { lg: 'none', xs: 'inline-block' }
}}
>
<Tooltip arrow title="Toggle Menu">
<IconButton sx={{ color: 'white' }} onClick={toggleSidebar}>
{!sidebarToggle ? (
<MenuTwoToneIcon fontSize="small" />
) : (
<CloseTwoToneIcon fontSize="small" />
)}
</IconButton>
</Tooltip>
</Box>
<Stack
direction="row"
divider={<Divider orientation="vertical" flexItem />}
@ -79,23 +102,6 @@ function Header(props: HeaderProps) {
/>
<HeaderUserbox />
<Box
component="span"
sx={{
ml: 2,
display: { lg: 'none', xs: 'inline-block' }
}}
>
<Tooltip arrow title="Toggle Menu">
<IconButton color="primary" onClick={toggleSidebar}>
{!sidebarToggle ? (
<MenuTwoToneIcon fontSize="small" />
) : (
<CloseTwoToneIcon fontSize="small" />
)}
</IconButton>
</Tooltip>
</Box>
</Box>
</HeaderWrapper>
);

View File

@ -14,6 +14,7 @@ import { SidebarContext } from 'src/contexts/SidebarContext';
import BrightnessLowTwoToneIcon from '@mui/icons-material/BrightnessLowTwoTone';
import TableChartTwoToneIcon from '@mui/icons-material/TableChartTwoTone';
import { FormattedMessage } from 'react-intl';
import { UserContext } from '../../../../contexts/userContext';
const MenuWrapper = styled(Box)(
({ theme }) => `
@ -159,6 +160,8 @@ const SubMenuWrapper = styled(Box)(
function SidebarMenu() {
const { closeSidebar } = useContext(SidebarContext);
const context = useContext(UserContext);
const { currentUser, setUser } = context;
return (
<>
@ -188,30 +191,33 @@ function SidebarMenu() {
</List>
</SubMenuWrapper>
</List>
<List
component="div"
subheader={
<ListSubheader component="div" disableSticky>
Management
</ListSubheader>
}
>
<SubMenuWrapper>
<List component="div">
<ListItem component="div">
<Button
disableRipple
component={RouterLink}
onClick={closeSidebar}
to="/users"
startIcon={<TableChartTwoToneIcon />}
>
<FormattedMessage id="users" defaultMessage="Users" />
</Button>
</ListItem>
</List>
</SubMenuWrapper>
</List>
{currentUser.hasWriteAccess && (
<List
component="div"
subheader={
<ListSubheader component="div" disableSticky>
Management
</ListSubheader>
}
>
<SubMenuWrapper>
<List component="div">
<ListItem component="div">
<Button
disableRipple
component={RouterLink}
onClick={closeSidebar}
to="/users"
startIcon={<TableChartTwoToneIcon />}
>
<FormattedMessage id="users" defaultMessage="Users" />
</Button>
</ListItem>
</List>
</SubMenuWrapper>
</List>
)}
</MenuWrapper>
</>
);

View File

@ -1,13 +1,13 @@
import { useContext } from 'react';
import Scrollbar from 'src/components/Scrollbar';
import { SidebarContext } from 'src/contexts/SidebarContext';
import innovenergyLogo from 'src/Resources/innoveng_logo_on_orange.png';
import innovenergyLogo from 'src/Resources/images/innovenergy-Logo_Speichern-mit-Salz_R_color.svg';
import {
alpha,
Box,
darken,
Divider,
Drawer,
lighten,
styled,
useTheme
@ -18,7 +18,7 @@ import SidebarMenu from './SidebarMenu';
const SidebarWrapper = styled(Box)(
({ theme }) => `
width: ${theme.sidebar.width};
min-width: "${theme.sidebar.width}";
min-width: ${theme.sidebar.width};
color: ${theme.colors.alpha.trueWhite[70]};
position: relative;
z-index: 7;
@ -63,8 +63,7 @@ function Sidebar() {
src={innovenergyLogo}
alt="innovenergy logo"
style={{
maxWidth: '150px', // Maximum width for the image
maxHeight: '150px' // Maximum height for the image
width: '150px' // Width of the image
}}
/>
</Box>
@ -78,12 +77,53 @@ function Sidebar() {
/>
<SidebarMenu />
</Scrollbar>
<Divider
sx={{
background: theme.colors.alpha.trueWhite[10]
}}
/>
</SidebarWrapper>
<Drawer
sx={{
boxShadow: `${theme.sidebar.boxShadow}`
}}
anchor={theme.direction === 'rtl' ? 'right' : 'left'}
open={sidebarToggle}
onClose={closeSidebar}
variant="temporary"
elevation={9}
>
<SidebarWrapper
sx={{
background:
theme.palette.mode === 'dark'
? theme.colors.alpha.white[100]
: darken(theme.colors.alpha.black[100], 0.5)
}}
>
<Scrollbar>
<Box mt={3}>
<Box
mx={2}
sx={{
width: 52
}}
>
<img
src={innovenergyLogo}
alt="innovenergy logo"
style={{
width: '150px' // Width of the image
}}
/>
</Box>
</Box>
<Divider
sx={{
mt: theme.spacing(3),
mx: theme.spacing(2),
background: theme.colors.alpha.trueWhite[10]
}}
/>
<SidebarMenu />
</Scrollbar>
</SidebarWrapper>
</Drawer>
</>
);
}

View File

@ -1,14 +1,14 @@
{
"installation": "installation/",
"liveView": "liveView/",
"users": "/users/",
"log": "log/",
"installations": "/installations/",
"groups": "/groups/",
"group": "group/",
"folder": "folder/",
"manageAccess": "manageAccess/",
"user": "user/",
"tree": "tree/",
"list": "list/"
}
{
"installation": "installation/",
"liveView": "liveView/",
"users": "/users/",
"log": "log/",
"installations": "/installations/",
"groups": "/groups/",
"group": "group/",
"folder": "folder/",
"manageAccess": "manageAccess/",
"user": "user/",
"tree": "tree/",
"list": "list/"
}