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
28 changes: 28 additions & 0 deletions netmanager/src/utils/hooks/useMaintenanceStatus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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();
setMaintenance(response.maintenance);
} catch (err) {
setError(err);
} 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,38 @@
import React from 'react';
import { makeStyles } from '@material-ui/styles';
import { Alert } from '@material-ui/lab';
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';


const useStyles = makeStyles((theme) => ({
banner: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
zIndex: 9999,
'& .MuiAlert-message': {
width: '100%',
textAlign: 'center'
}
}
}));

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

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

return (
<Alert severity="warning" className={classes.banner}>
{maintenance.message || 'System maintenance in progress. Some features may be unavailable.'}
Estimated downtime: {formatDateString(maintenance.startDate)} -{' '}
{formatDateString(maintenance.endDate)}
</Alert>
);
};

export default MaintenanceBanner;
2 changes: 2 additions & 0 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 @@ -164,6 +165,7 @@ const Main = (props) => {
[classes.shiftContent]: isDesktop
})}
>
<MaintenanceBanner />
<Topbar toggleSidebar={toggleSidebar} />
<div style={{ position: 'relative' }}>
<HorizontalLoader loading={loaderStatus} />
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
25 changes: 13 additions & 12 deletions netmanager/src/views/pages/UserList/UserList.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ const UserList = (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);
Comment on lines +31 to +32
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider extracting shared pagination logic.

The pagination implementation is duplicated between UserList.js and AvailableUserList.js. This includes state management, fetch logic, and page calculation.

Consider creating a custom hook to share this logic:

// usePagination.js
const usePagination = (fetchFn, initialLimit = 10) => {
  const [limit, setLimit] = useState(initialLimit);
  const [skip, setSkip] = useState(0);

  const handlePageChange = (page, pageSize) => {
    if (page < 0 || pageSize <= 0) return;
    const newSkip = page * pageSize;
    if (newSkip >= Number.MAX_SAFE_INTEGER) return;
    setSkip(newSkip);
    setLimit(pageSize);
    fetchFn(newSkip, pageSize);
  };

  return {
    limit,
    skip,
    currentPage: skip / limit,
    handlePageChange
  };
};

This would reduce code duplication and centralize the edge case handling.

Also applies to: 41-47, 77-81, 94-95

const roles = useSelector((state) => state.accessControl.rolesSummary);
const activeNetwork = useSelector((state) => state.accessControl.activeNetwork);

Expand All @@ -38,13 +38,13 @@ const UserList = (props) => {
dispatch(loadRolesSummary(activeNetwork._id));
}, []);

const fetchUsers = async (page, limit) => {
const fetchUsers = async (skipCount, limitCount) => {
if (!activeNetwork) return;
setLoading(true);
try {
const res = await getNetworkUsersListApi(activeNetwork._id, {
page: page + 1,
limit
skip: skipCount,
limit: limitCount
});
setUsers(res.assigned_users);
setTotalCount(res.total || 0);
Expand All @@ -71,13 +71,14 @@ const UserList = (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 @@ -90,8 +91,8 @@ const UserList = (props) => {
users={users}
loadData={loading}
totalCount={totalCount}
pageSize={pageSize}
currentPage={currentPage}
pageSize={limit}
currentPage={skip / limit}
onPageChange={handlePageChange}
/>
</div>
Expand Down
Loading