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`;
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 };
};
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,39 @@
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. SoformatDate(me features may be unavailable.'}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in default maintenance message.

There appears to be a typo in the default message: "SoformatDate(me" should likely be "Some".

-      {maintenance.message ||
-        'System maintenance in progress. SoformatDate(me features may be unavailable.'}
+      {maintenance.message ||
+        'System maintenance in progress. Some features may be unavailable.'}
📝 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
{maintenance.message ||
'System maintenance in progress. SoformatDate(me features may be unavailable.'}
{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
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