• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 947088195

pending completion
947088195

Pull #2661

gitlab-ci

mzedel
chore: improved device filter scrolling behaviour

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #2661: chore: added lint rules for hooks usage

4411 of 6415 branches covered (68.76%)

297 of 440 new or added lines in 62 files covered. (67.5%)

1617 existing lines in 163 files now uncovered.

8311 of 10087 relevant lines covered (82.39%)

192.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

52.33
/src/js/components/devices/device-groups.js
1
// Copyright 2018 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useCallback, useEffect, useRef, useState } from 'react';
15
import { useDispatch, useSelector } from 'react-redux';
16
import { useParams } from 'react-router-dom';
17

18
import { AddCircle as AddIcon } from '@mui/icons-material';
19
import { Dialog, DialogContent, DialogTitle } from '@mui/material';
20

21
import pluralize from 'pluralize';
22

23
import { setOfflineThreshold } from '../../actions/appActions';
24
import {
25
  addDynamicGroup,
26
  addStaticGroup,
27
  removeDevicesFromGroup,
28
  removeDynamicGroup,
29
  removeStaticGroup,
30
  selectGroup,
31
  setDeviceFilters,
32
  setDeviceListState,
33
  updateDynamicGroup
34
} from '../../actions/deviceActions';
35
import { setShowConnectingDialog } from '../../actions/userActions';
36
import { SORTING_OPTIONS } from '../../constants/appConstants';
37
import { DEVICE_FILTERING_OPTIONS, DEVICE_ISSUE_OPTIONS, DEVICE_STATES, emptyFilter } from '../../constants/deviceConstants';
38
import { toggle } from '../../helpers';
39
import {
40
  getAcceptedDevices,
41
  getDeviceCountsByStatus,
42
  getDeviceFilters,
43
  getDeviceLimit,
44
  getFeatures,
45
  getGroups as getGroupsSelector,
46
  getIsEnterprise,
47
  getIsPreview,
48
  getLimitMaxed,
49
  getSelectedGroupInfo,
50
  getShowHelptips,
51
  getSortedFilteringAttributes,
52
  getTenantCapabilities,
53
  getUserCapabilities
54
} from '../../selectors';
55
import { useLocationParams } from '../../utils/liststatehook';
56
import Global from '../settings/global';
57
import AuthorizedDevices from './authorized-devices';
58
import DeviceStatusNotification from './devicestatusnotification';
59
import MakeGatewayDialog from './dialogs/make-gateway-dialog';
60
import PreauthDialog, { DeviceLimitWarning } from './dialogs/preauth-dialog';
61
import CreateGroup from './group-management/create-group';
62
import CreateGroupExplainer from './group-management/create-group-explainer';
63
import RemoveGroup from './group-management/remove-group';
64
import Groups from './groups';
65
import DeviceAdditionWidget from './widgets/deviceadditionwidget';
66

67
export const DeviceGroups = () => {
4✔
68
  const [createGroupExplanation, setCreateGroupExplanation] = useState(false);
2✔
69
  const [fromFilters, setFromFilters] = useState(false);
2✔
70
  const [modifyGroupDialog, setModifyGroupDialog] = useState(false);
2✔
71
  const [openIdDialog, setOpenIdDialog] = useState(false);
2✔
72
  const [openPreauth, setOpenPreauth] = useState(false);
2✔
73
  const [showMakeGateway, setShowMakeGateway] = useState(false);
2✔
74
  const [removeGroup, setRemoveGroup] = useState(false);
2✔
75
  const [tmpDevices, setTmpDevices] = useState([]);
2✔
76
  const { status: statusParam } = useParams();
2✔
77

78
  const { groupCount, selectedGroup, groupFilters = [] } = useSelector(getSelectedGroupInfo);
2!
79
  const filteringAttributes = useSelector(getSortedFilteringAttributes);
2✔
80
  const { canManageDevices } = useSelector(getUserCapabilities);
2✔
81
  const tenantCapabilities = useSelector(getTenantCapabilities);
2✔
82
  const { groupNames, ...groupsByType } = useSelector(getGroupsSelector);
2✔
83
  const groups = groupNames;
2✔
84
  const { total: acceptedCount = 0 } = useSelector(getAcceptedDevices);
2!
85
  const authRequestCount = useSelector(state => state.monitor.issueCounts.byType[DEVICE_ISSUE_OPTIONS.authRequests.key].total);
5✔
86
  const canPreview = useSelector(getIsPreview);
2✔
87
  const deviceLimit = useSelector(getDeviceLimit);
2✔
88
  const deviceListState = useSelector(state => state.devices.deviceList);
5✔
89
  const features = useSelector(getFeatures);
2✔
90
  const { hasReporting } = features;
2✔
91
  const filters = useSelector(getDeviceFilters);
2✔
92
  const limitMaxed = useSelector(getLimitMaxed);
2✔
93
  const { pending: pendingCount } = useSelector(getDeviceCountsByStatus);
2✔
94
  const showDeviceConnectionDialog = useSelector(state => state.users.showConnectDeviceDialog);
5✔
95
  const showHelptips = useSelector(getShowHelptips);
2✔
96
  const isEnterprise = useSelector(getIsEnterprise);
2✔
97
  const dispatch = useDispatch();
2✔
98
  const isInitialized = useRef(false);
2✔
99

100
  const [locationParams, setLocationParams] = useLocationParams('devices', {
2✔
101
    filteringAttributes,
102
    filters,
103
    defaults: { sort: { direction: SORTING_OPTIONS.desc } }
104
  });
105

106
  const { refreshTrigger, selectedId, state: selectedState } = deviceListState;
2✔
107

108
  const refreshListState = useCallback(() => dispatch(setDeviceListState({ refreshTrigger: !refreshTrigger })), [dispatch, refreshTrigger]);
2✔
109

110
  useEffect(() => {
2✔
111
    if (!isInitialized.current) {
2!
112
      return;
2✔
113
    }
UNCOV
114
    setLocationParams({ pageState: deviceListState, filters, selectedGroup });
×
115
    // eslint-disable-next-line react-hooks/exhaustive-deps
116
  }, [
117
    deviceListState.detailsTab,
118
    deviceListState.page,
119
    deviceListState.perPage,
120
    deviceListState.selectedIssues,
121
    // eslint-disable-next-line react-hooks/exhaustive-deps
122
    JSON.stringify(deviceListState.sort),
123
    refreshTrigger,
124
    selectedId,
125
    filters,
126
    selectedGroup,
127
    selectedState,
128
    setLocationParams
129
  ]);
130

131
  useEffect(() => {
2✔
132
    const { groupName, filters = [], id = [], ...remainder } = locationParams;
1!
133
    const { hasFullFiltering } = tenantCapabilities;
1✔
134
    if (groupName) {
1!
UNCOV
135
      dispatch(selectGroup(groupName, filters));
×
136
    } else if (filters.length) {
1!
UNCOV
137
      dispatch(setDeviceFilters(filters));
×
138
    }
139
    let listState = { ...remainder };
1✔
140
    if (statusParam && Object.values(DEVICE_STATES).some(state => state === statusParam)) {
1!
NEW
141
      listState.state = statusParam;
×
142
    }
143
    if (id.length === 1 && Boolean(locationParams.open)) {
1!
UNCOV
144
      listState.selectedId = id[0];
×
145
    } else if (id.length && hasFullFiltering) {
1!
UNCOV
146
      dispatch(setDeviceFilters([...filters, { ...emptyFilter, key: 'id', operator: DEVICE_FILTERING_OPTIONS.$in.key, value: id }]));
×
147
    }
148
    dispatch(setDeviceListState(listState)).then(() => {
1✔
NEW
149
      if (isInitialized.current) {
×
NEW
150
        return;
×
151
      }
NEW
152
      isInitialized.current = true;
×
NEW
153
      refreshListState();
×
NEW
154
      dispatch(setOfflineThreshold());
×
155
    });
156
    // eslint-disable-next-line react-hooks/exhaustive-deps
157
  }, [dispatch, JSON.stringify(tenantCapabilities), JSON.stringify(locationParams), statusParam]);
158

159
  /*
160
   * Groups
161
   */
162
  const removeCurrentGroup = () => {
2✔
UNCOV
163
    const request = groupFilters.length ? dispatch(removeDynamicGroup(selectedGroup)) : dispatch(removeStaticGroup(selectedGroup));
×
UNCOV
164
    return request.then(toggleGroupRemoval).catch(console.log);
×
165
  };
166

167
  // Edit groups from device selection
168
  const addDevicesToGroup = tmpDevices => {
2✔
169
    // (save selected devices in state, open dialog)
UNCOV
170
    setTmpDevices(tmpDevices);
×
UNCOV
171
    setModifyGroupDialog(toggle);
×
172
  };
173

174
  const createGroupFromDialog = (devices, group) => {
2✔
UNCOV
175
    let request = fromFilters ? dispatch(addDynamicGroup(group, filters)) : dispatch(addStaticGroup(group, devices));
×
UNCOV
176
    return request.then(() => {
×
177
      // reached end of list
UNCOV
178
      setCreateGroupExplanation(false);
×
UNCOV
179
      setModifyGroupDialog(false);
×
UNCOV
180
      setFromFilters(false);
×
181
    });
182
  };
183

184
  const onGroupClick = () => {
2✔
UNCOV
185
    if (selectedGroup && groupFilters.length) {
×
UNCOV
186
      return dispatch(updateDynamicGroup(selectedGroup, filters));
×
187
    }
UNCOV
188
    setModifyGroupDialog(true);
×
UNCOV
189
    setFromFilters(true);
×
190
  };
191

192
  const onRemoveDevicesFromGroup = devices => {
2✔
UNCOV
193
    const isGroupRemoval = devices.length >= groupCount;
×
194
    let request;
UNCOV
195
    if (isGroupRemoval) {
×
UNCOV
196
      request = dispatch(removeStaticGroup(selectedGroup));
×
197
    } else {
UNCOV
198
      request = dispatch(removeDevicesFromGroup(selectedGroup, devices));
×
199
    }
UNCOV
200
    return request.catch(console.log);
×
201
  };
202

203
  const openSettingsDialog = e => {
2✔
UNCOV
204
    e.preventDefault();
×
UNCOV
205
    setOpenIdDialog(toggle);
×
206
  };
207

208
  const onCreateGroupClose = () => {
2✔
UNCOV
209
    setModifyGroupDialog(false);
×
UNCOV
210
    setFromFilters(false);
×
UNCOV
211
    setTmpDevices([]);
×
212
  };
213

214
  const onPreauthSaved = addMore => {
2✔
UNCOV
215
    setOpenPreauth(!addMore);
×
UNCOV
216
    dispatch(setDeviceListState({ page: 1, refreshTrigger: !refreshTrigger }));
×
217
  };
218

219
  const onShowDeviceStateClick = state => {
2✔
UNCOV
220
    dispatch(selectGroup());
×
UNCOV
221
    dispatch(setDeviceListState({ state }));
×
222
  };
223

224
  const onGroupSelect = groupName => {
2✔
UNCOV
225
    dispatch(selectGroup(groupName));
×
UNCOV
226
    dispatch(setDeviceListState({ page: 1, refreshTrigger: !refreshTrigger, selection: [] }));
×
227
  };
228

229
  const onShowAuthRequestDevicesClick = () => {
2✔
UNCOV
230
    dispatch(setDeviceFilters([]));
×
UNCOV
231
    dispatch(setDeviceListState({ selectedIssues: [DEVICE_ISSUE_OPTIONS.authRequests.key], page: 1 }));
×
232
  };
233

234
  const toggleGroupRemoval = () => setRemoveGroup(toggle);
2✔
235

236
  const toggleMakeGatewayClick = () => setShowMakeGateway(toggle);
2✔
237

238
  return (
2✔
239
    <>
240
      <div className="tab-container with-sub-panels" style={{ paddingTop: 0, paddingBottom: 45, minHeight: 'max-content', alignContent: 'center' }}>
241
        <h3 className="flexbox center-aligned" style={{ marginBottom: 0, marginTop: 0, flexWrap: 'wrap' }}>
242
          Devices
243
        </h3>
244
        <span className="flexbox space-between margin-left-large margin-right center-aligned">
245
          {hasReporting && !!authRequestCount && (
2!
246
            <a className="flexbox center-aligned margin-right-large" onClick={onShowAuthRequestDevicesClick}>
247
              <AddIcon fontSize="small" style={{ marginRight: 6 }} />
248
              {authRequestCount} new device authentication {pluralize('request', authRequestCount)}
249
            </a>
250
          )}
251
          {!!pendingCount && !selectedGroup && selectedState !== DEVICE_STATES.pending ? (
6!
252
            <DeviceStatusNotification deviceCount={pendingCount} state={DEVICE_STATES.pending} onClick={onShowDeviceStateClick} />
253
          ) : (
254
            <div />
255
          )}
256
          {canManageDevices && (
4✔
257
            <DeviceAdditionWidget
258
              features={features}
UNCOV
259
              onConnectClick={() => dispatch(setShowConnectingDialog(true))}
×
260
              onMakeGatewayClick={toggleMakeGatewayClick}
261
              onPreauthClick={setOpenPreauth}
262
              tenantCapabilities={tenantCapabilities}
263
            />
264
          )}
265
        </span>
266
      </div>
267
      <div className="tab-container with-sub-panels" style={{ padding: 0, height: '100%' }}>
268
        <Groups
269
          className="leftFixed"
270
          acceptedCount={acceptedCount}
271
          changeGroup={onGroupSelect}
272
          groups={groupsByType}
273
          openGroupDialog={setCreateGroupExplanation}
274
          selectedGroup={selectedGroup}
275
          showHelptips={showHelptips}
276
        />
277
        <div className="rightFluid relative" style={{ paddingTop: 0 }}>
278
          {limitMaxed && <DeviceLimitWarning acceptedDevices={acceptedCount} deviceLimit={deviceLimit} />}
2!
279
          <AuthorizedDevices
280
            addDevicesToGroup={addDevicesToGroup}
281
            onGroupClick={onGroupClick}
282
            onGroupRemoval={toggleGroupRemoval}
283
            onMakeGatewayClick={toggleMakeGatewayClick}
284
            onPreauthClick={setOpenPreauth}
285
            openSettingsDialog={openSettingsDialog}
286
            removeDevicesFromGroup={onRemoveDevicesFromGroup}
287
            showsDialog={showDeviceConnectionDialog || removeGroup || modifyGroupDialog || createGroupExplanation || openIdDialog || openPreauth}
12✔
288
          />
289
        </div>
290
        {removeGroup && <RemoveGroup onClose={toggleGroupRemoval} onRemove={removeCurrentGroup} />}
2!
291
        {modifyGroupDialog && (
2!
292
          <CreateGroup
293
            addListOfDevices={createGroupFromDialog}
294
            fromFilters={fromFilters}
295
            isCreation={fromFilters || !groups.length}
×
296
            selectedDevices={tmpDevices}
297
            onClose={onCreateGroupClose}
298
          />
299
        )}
UNCOV
300
        {createGroupExplanation && <CreateGroupExplainer isEnterprise={isEnterprise} onClose={() => setCreateGroupExplanation(false)} />}
×
301
        {openIdDialog && (
2!
302
          <Dialog open>
303
            <DialogTitle>Default device identity attribute</DialogTitle>
304
            <DialogContent style={{ overflow: 'hidden' }}>
305
              <Global dialog closeDialog={openSettingsDialog} />
306
            </DialogContent>
307
          </Dialog>
308
        )}
309
        {openPreauth && (
2!
310
          <PreauthDialog
311
            acceptedDevices={acceptedCount}
312
            deviceLimit={deviceLimit}
313
            limitMaxed={limitMaxed}
314
            onSubmit={onPreauthSaved}
UNCOV
315
            onCancel={() => setOpenPreauth(false)}
×
316
          />
317
        )}
318
        {showMakeGateway && <MakeGatewayDialog isPreRelease={canPreview} onCancel={toggleMakeGatewayClick} />}
2!
319
      </div>
320
    </>
321
  );
322
};
323

324
export default DeviceGroups;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc