Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Netmanager] Added maintenance banner, fixed sidebar, use skip for pagination #2300

Merged
merged 10 commits into from
Dec 5, 2024
2 changes: 2 additions & 0 deletions netmanager/src/config/urls/authService.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ export const USER_FEEDBACK_URI = `${BASE_AUTH_SERVICE_URL_V2}/users/feedback`;
export const GET_ACCESS_TOKEN = `${BASE_AUTH_SERVICE_URL_V2}/users/tokens`;

export const GET_LOGS = `${BASE_AUTH_SERVICE_URL_V2}/users/logs`;

export const GET_MAINTENANCE_STATUS = `${BASE_AUTH_SERVICE_URL_V2}/users/maintenances/analytics`;
60 changes: 34 additions & 26 deletions netmanager/src/redux/AccessControl/operations.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,36 +77,44 @@ export const addActiveNetwork = (data) => (dispatch) => {
});
};

export const fetchNetworkUsers = (networkId) => async (dispatch) => {
return await getNetworkUsersListApi(networkId)
.then((resData) => {
dispatch({
type: LOAD_NETWORK_USERS_SUCCESS,
payload: resData.assigned_users
});
})
.catch((err) => {
dispatch({
type: LOAD_NETWORK_USERS_FAILURE,
payload: err
});
export const fetchNetworkUsers = (networkId, params) => async (dispatch) => {
try {
const resData = await getNetworkUsersListApi(networkId, params);
dispatch({
type: LOAD_NETWORK_USERS_SUCCESS,
payload: {
users: resData.assigned_users,
total: resData.total_assigned_users
}
});
return resData;
} catch (err) {
dispatch({
type: LOAD_NETWORK_USERS_FAILURE,
payload: err
});
throw err;
}
};

export const fetchAvailableNetworkUsers = (networkId) => async (dispatch) => {
return await getAvailableNetworkUsersListApi(networkId)
.then((resData) => {
dispatch({
type: LOAD_AVAILABLE_USERS_SUCCESS,
payload: resData.available_users
});
})
.catch((err) => {
dispatch({
type: LOAD_AVAILABLE_USERS_FAILURE,
payload: err
});
export const fetchAvailableNetworkUsers = (networkId, params) => async (dispatch) => {
try {
const resData = await getAvailableNetworkUsersListApi(networkId, params);
dispatch({
type: LOAD_AVAILABLE_USERS_SUCCESS,
payload: {
users: resData.available_users,
total: resData.total_available_users
}
});
return resData;
} catch (err) {
dispatch({
type: LOAD_AVAILABLE_USERS_FAILURE,
payload: err
});
throw err;
}
};

export const addUserGroupSummary = (data) => (dispatch) => {
Expand Down
26 changes: 22 additions & 4 deletions netmanager/src/redux/AccessControl/reducers.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@ const initialState = {
currentRole: {},
userNetworks: null,
activeNetwork: {},
networkUsers: null,
networkUsers: {
users: null,
total: 0
},
rolesSummary: null,
availableUsers: null,
availableUsers: {
users: null,
total: 0
},
groupsSummary: null
};

Expand All @@ -32,11 +38,23 @@ export default function accessControlReducer(state = initialState, action) {
case LOAD_CURRENT_NETWORK_SUCCESS:
return { ...state, activeNetwork: action.payload };
case LOAD_NETWORK_USERS_SUCCESS:
return { ...state, networkUsers: action.payload };
return {
...state,
networkUsers: {
users: action.payload.users,
total: action.payload.total
}
};
case LOAD_ROLES_SUMMARY_SUCCESS:
return { ...state, rolesSummary: action.payload };
case LOAD_AVAILABLE_USERS_SUCCESS:
return { ...state, availableUsers: action.payload };
return {
...state,
availableUsers: {
users: action.payload.users,
total: action.payload.total
}
};
case LOAD_GROUPS_SUMMARY_SUCCESS:
return { ...state, groupsSummary: action.payload };
default:
Expand Down
35 changes: 35 additions & 0 deletions netmanager/src/utils/hooks/useMaintenanceStatus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useState, useEffect } from 'react';
import { getMaintenanceStatusApi } from 'views/apis/authService';

export const useMaintenanceStatus = () => {
const [maintenance, setMaintenance] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
const checkMaintenanceStatus = async () => {
try {
const response = await getMaintenanceStatusApi();
if (response.success && response.maintenance?.length > 0) {
// Get the first active maintenance
const activeMaintenance = response.maintenance.find((m) => m.isActive);
setMaintenance(activeMaintenance || null);
} else {
setMaintenance(null);
}
} catch (err) {
setError(err);
setMaintenance(null);
} finally {
setLoading(false);
}
};

checkMaintenanceStatus();
// Check every 5 minutes
const interval = setInterval(checkMaintenanceStatus, 5 * 60 * 1000);
return () => clearInterval(interval);
}, []);

return { maintenance, loading, error };
};
8 changes: 4 additions & 4 deletions netmanager/src/views/apis/accessControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ export const assignUserNetworkApi = async (networkID, userID) => {
.then((response) => response.data);
};

export const getAvailableNetworkUsersListApi = async (networkID) => {
export const getAvailableNetworkUsersListApi = async (networkId, params = {}) => {
return await createAxiosInstance()
.get(`${GET_NETWORKS_URI}/${networkID}/available-users`)
.get(`${GET_NETWORKS_URI}/${networkId}/available-users`, { params })
.then((response) => response.data);
};

Expand Down Expand Up @@ -111,9 +111,9 @@ export const updatePermissionsToRoleApi = async (roleID, data) => {
.then((response) => response.data);
};

export const getNetworkUsersListApi = async (networkID) => {
export const getNetworkUsersListApi = async (networkId, params = {}) => {
return await createAxiosInstance()
.get(`${GET_NETWORKS_URI}/${networkID}/assigned-users`)
.get(`${GET_NETWORKS_URI}/${networkId}/assigned-users`, { params })
.then((response) => response.data);
};

Expand Down
9 changes: 8 additions & 1 deletion netmanager/src/views/apis/authService.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import {
REGISTER_USER_URI,
CHART_DEFAULTS_URI,
USER_FEEDBACK_URI,
GET_LOGS
GET_LOGS,
GET_MAINTENANCE_STATUS
} from 'config/urls/authService';
import createAxiosInstance from './axiosConfig';
import { BASE_AUTH_SERVICE_URL_V2 } from '../../config/urls/authService';
Expand Down Expand Up @@ -109,3 +110,9 @@ export const updateDefaultSelectedSiteApi = async (siteId, siteData) => {
.put(`${BASE_AUTH_SERVICE_URL_V2}/users/preferences/selected-sites/${siteId}`, siteData)
.then((response) => response.data);
};

export const getMaintenanceStatusApi = async () => {
return await createAxiosInstance()
.get(GET_MAINTENANCE_STATUS)
.then((response) => response.data);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import React from 'react';
import { makeStyles } from '@material-ui/styles';
import { Paper, Typography, Box } from '@material-ui/core';
import { Warning as WarningIcon } from '@material-ui/icons';
import { useMaintenanceStatus } from 'utils/hooks/useMaintenanceStatus';
import { formatDateString } from '../../../utils/dateTime';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove unused import

The formatDateString import is not used in the component. Consider removing it.

-import { formatDateString } from '../../../utils/dateTime';

import { format } from 'date-fns';

const useStyles = makeStyles((theme) => ({
banner: {
padding: theme.spacing(2),
backgroundColor: '#fff3e0', // Light warning color
border: '1px solid #ffb74d', // Warning border
borderRadius: '4px',
marginBottom: theme.spacing(2),
margin: 5
},
content: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: theme.spacing(2)
},
icon: {
color: '#f57c00' // Warning icon color
},
message: {
color: '#424242', // Dark text for readability
fontWeight: 'bold',
fontSize: 18
},
timeInfo: {
marginTop: theme.spacing(1),
color: '#616161', // Slightly lighter text for secondary info
fontSize: '0.875rem',
textAlign: 'center'
}
}));

const MaintenanceBanner = () => {
const classes = useStyles();
const { maintenance, loading } = useMaintenanceStatus();

if (loading || !maintenance || !maintenance.isActive) {
return null;
}

return (
<Paper elevation={0} className={classes.banner}>
<Box className={classes.content}>
<WarningIcon className={classes.icon} />
<Typography variant="body1" className={classes.message}>
{maintenance.message ||
'System maintenance in progress. Some features may be unavailable.'}
</Typography>
</Box>
<Typography variant="body2" className={classes.timeInfo}>
Estimated downtime: {format(new Date(maintenance.startDate), 'MMM d, yyyy h:mm a')} -{' '}
{format(new Date(maintenance.endDate), 'MMM d, yyyy h:mm a')}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add date validation

Consider adding error handling for invalid date values to prevent runtime errors.

-        Estimated downtime: {format(new Date(maintenance.startDate), 'MMM d, yyyy h:mm a')} -{' '}
-        {format(new Date(maintenance.endDate), 'MMM d, yyyy h:mm a')}
+        Estimated downtime: {
+          maintenance.startDate && !isNaN(new Date(maintenance.startDate))
+            ? format(new Date(maintenance.startDate), 'MMM d, yyyy h:mm a')
+            : 'Invalid start date'
+        } -{' '}
+        {
+          maintenance.endDate && !isNaN(new Date(maintenance.endDate))
+            ? format(new Date(maintenance.endDate), 'MMM d, yyyy h:mm a')
+            : 'Invalid end date'
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Estimated downtime: {format(new Date(maintenance.startDate), 'MMM d, yyyy h:mm a')} -{' '}
{format(new Date(maintenance.endDate), 'MMM d, yyyy h:mm a')}
Estimated downtime: {
maintenance.startDate && !isNaN(new Date(maintenance.startDate))
? format(new Date(maintenance.startDate), 'MMM d, yyyy h:mm a')
: 'Invalid start date'
} -{' '}
{
maintenance.endDate && !isNaN(new Date(maintenance.endDate))
? format(new Date(maintenance.endDate), 'MMM d, yyyy h:mm a')
: 'Invalid end date'
}

</Typography>
</Paper>
);
};

export default MaintenanceBanner;
9 changes: 7 additions & 2 deletions netmanager/src/views/layouts/Main.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '../../redux/AccessControl/operations';
import { LargeCircularLoader } from '../components/Loader/CircularLoader';
import { updateMainAlert } from '../../redux/MainAlert/operations';
import MaintenanceBanner from 'views/components/MaintenanceBanner/MaintenanceBanner';

const useStyles = makeStyles((theme) => ({
root: {
Expand Down Expand Up @@ -149,7 +150,7 @@ const Main = (props) => {
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
width: '100vw'
width: '100%'
}}
>
<LargeCircularLoader loading={loading} size={50} height={50} />
Expand All @@ -174,7 +175,11 @@ const Main = (props) => {
open={shouldOpenSidebar}
variant={isDesktop ? 'persistent' : 'temporary'}
/>
<main className={classes.content}>{children}</main>

<main className={classes.content}>
<MaintenanceBanner />
{children}
</main>
<Footer />
</div>
);
Expand Down
4 changes: 0 additions & 4 deletions netmanager/src/views/layouts/common/Sidebar/Sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,6 @@ const Sidebar = (props) => {
// check whether user has a role
const currentUser = JSON.parse(localStorage.getItem('currentUser'));

if (isEmpty(currentUser)) {
return;
}

if (!isEmpty(currentUser)) {
if (!isEmpty(currentRole)) {
if (currentRole.role_permissions) {
Expand Down
2 changes: 1 addition & 1 deletion netmanager/src/views/pages/ExportData/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ const ExportData = (props) => {
startDateTime: roundToStartOfDay(new Date(startDate).toISOString()),
endDateTime: roundToEndOfDay(new Date(endDate).toISOString()),
sites: sitesList,
device: getValues(selectedDevices),
devices: getValues(selectedDevices),
airqlouds: getValues(selectedAirqlouds),
network: activeNetwork.net_name,
datatype: dataType.value,
Expand Down
27 changes: 13 additions & 14 deletions netmanager/src/views/pages/UserList/AvailableUserList.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import PropTypes from 'prop-types';
import usrsStateConnector from 'views/stateConnectors/usersStateConnector';
import ErrorBoundary from 'views/ErrorBoundary/ErrorBoundary';
import { useDispatch, useSelector } from 'react-redux';
import { isEmpty } from 'underscore';
import { withPermission } from '../../containers/PageAccess';
import AvailableUsersTable from './components/UsersTable/AvailableUsersTable';
import { getAvailableNetworkUsersListApi } from 'views/apis/accessControl';
Expand All @@ -26,17 +25,17 @@ const AvailableUserList = (props) => {
const [loading, setLoading] = useState(false);
const [users, setUsers] = useState([]);
const [totalCount, setTotalCount] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [currentPage, setCurrentPage] = useState(0);
const [limit, setLimit] = useState(10);
const [skip, setSkip] = useState(0);
const activeNetwork = useSelector((state) => state.accessControl.activeNetwork);

const fetchUsers = async (page, limit) => {
const fetchUsers = async (skipCount, limitCount) => {
if (!activeNetwork) return;
setLoading(true);
try {
const res = await getAvailableNetworkUsersListApi(activeNetwork._id, {
page: page + 1, // API expects 1-based pages
limit
skip: skipCount,
limit: limitCount
});
setUsers(res.available_users);
setTotalCount(res.total || 0);
Expand All @@ -61,15 +60,15 @@ const AvailableUserList = (props) => {
}
};

// Initial load
useEffect(() => {
fetchUsers(currentPage, pageSize);
fetchUsers(skip, limit);
}, [activeNetwork]);

const handlePageChange = (newPage, newPageSize) => {
setCurrentPage(newPage);
setPageSize(newPageSize);
fetchUsers(newPage, newPageSize);
const handlePageChange = (page, pageSize) => {
const newSkip = page * pageSize;
setSkip(newSkip);
setLimit(pageSize);
fetchUsers(newSkip, pageSize);
};

return (
Expand All @@ -80,8 +79,8 @@ const AvailableUserList = (props) => {
users={users}
loadData={loading}
totalCount={totalCount}
pageSize={pageSize}
currentPage={currentPage}
pageSize={limit}
currentPage={skip / limit}
onPageChange={handlePageChange}
/>
</div>
Expand Down
Loading
Loading