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

mendersoftware / gui / 1301920191

23 May 2024 07:13AM UTC coverage: 83.42% (-16.5%) from 99.964%
1301920191

Pull #4421

gitlab-ci

mzedel
fix: fixed an issue that sometimes prevented reopening paginated auditlog links

Ticket: None
Changelog: Title
Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4421: MEN-7034 - device information in auditlog entries

4456 of 6367 branches covered (69.99%)

34 of 35 new or added lines in 7 files covered. (97.14%)

1668 existing lines in 162 files now uncovered.

8473 of 10157 relevant lines covered (83.42%)

140.52 hits per line

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

61.06
/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, { useEffect, useRef, useState } from 'react';
15
import { useDispatch, useSelector } from 'react-redux';
16
import { useLocation, 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 * as DeviceConstants from '../../constants/deviceConstants.js';
39
import { onboardingSteps } from '../../constants/onboardingConstants';
40
import { toggle } from '../../helpers';
41
import {
42
  getAcceptedDevices,
43
  getDeviceCountsByStatus,
44
  getDeviceFilters,
45
  getDeviceLimit,
46
  getFeatures,
47
  getGroups as getGroupsSelector,
48
  getIsEnterprise,
49
  getIsPreview,
50
  getLimitMaxed,
51
  getOnboardingState,
52
  getSelectedGroupInfo,
53
  getSortedFilteringAttributes,
54
  getTenantCapabilities,
55
  getUserCapabilities
56
} from '../../selectors';
57
import { useLocationParams } from '../../utils/liststatehook';
58
import { getOnboardingComponentFor } from '../../utils/onboardingmanager';
59
import Global from '../settings/global';
60
import AuthorizedDevices from './authorized-devices';
61
import DeviceStatusNotification from './devicestatusnotification';
62
import MakeGatewayDialog from './dialogs/make-gateway-dialog';
63
import PreauthDialog, { DeviceLimitWarning } from './dialogs/preauth-dialog';
64
import CreateGroup from './group-management/create-group';
65
import CreateGroupExplainer from './group-management/create-group-explainer';
66
import RemoveGroup from './group-management/remove-group';
67
import Groups from './groups';
68
import DeviceAdditionWidget from './widgets/deviceadditionwidget';
69

70
export const DeviceGroups = () => {
3✔
71
  const [createGroupExplanation, setCreateGroupExplanation] = useState(false);
3✔
72
  const [fromFilters, setFromFilters] = useState(false);
3✔
73
  const [modifyGroupDialog, setModifyGroupDialog] = useState(false);
3✔
74
  const [openIdDialog, setOpenIdDialog] = useState(false);
3✔
75
  const [openPreauth, setOpenPreauth] = useState(false);
3✔
76
  const [showMakeGateway, setShowMakeGateway] = useState(false);
3✔
77
  const [removeGroup, setRemoveGroup] = useState(false);
3✔
78
  const [tmpDevices, setTmpDevices] = useState([]);
3✔
79
  const deviceConnectionRef = useRef();
3✔
80
  const { status: statusParam } = useParams();
3✔
81

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

105
  const [locationParams, setLocationParams] = useLocationParams('devices', {
3✔
106
    filteringAttributes,
107
    filters,
108
    defaults: { sort: { direction: SORTING_OPTIONS.desc } }
109
  });
110

111
  const { refreshTrigger, selectedId, state: selectedState } = deviceListState;
3✔
112

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

133
  useEffect(() => {
3✔
134
    // set isInitialized ref to false when location changes, otherwise when you go back setLocationParams will be set with a duplicate item
135
    isInitialized.current = false;
1✔
136
  }, [location]);
137

138
  useEffect(() => {
3✔
139
    const { groupName, filters = [], id = [], ...remainder } = locationParams;
1!
140
    const { hasFullFiltering } = tenantCapabilities;
1✔
141
    if (groupName) {
1!
142
      if (groupName != selectedGroup) {
1!
UNCOV
143
        dispatch(selectGroup(groupName, filters));
×
144
      }
145
    } else {
146
      // dispatch setDeviceFilters even when filters are empty, otherwise filter will not be reset
UNCOV
147
      dispatch(setDeviceFilters(filters));
×
148
      // if selected group exists in the state, but not set in locationParams then unset it
UNCOV
149
      selectedGroup && dispatch({ type: DeviceConstants.SELECT_GROUP, group: undefined });
×
150
    }
151
    // preset selectedIssues and selectedId with empty values, in case if remain properties are missing them
152
    let listState = { selectedIssues: [], selectedId: undefined, ...remainder };
1✔
153

154
    if (statusParam && Object.values(DEVICE_STATES).some(state => state === statusParam)) {
1!
UNCOV
155
      listState.state = statusParam;
×
156
    }
157

158
    if (id.length === 1 && Boolean(locationParams.open)) {
1!
UNCOV
159
      listState.selectedId = id[0];
×
160
    } else if (id.length && hasFullFiltering) {
1!
UNCOV
161
      dispatch(setDeviceFilters([...filters, { ...emptyFilter, key: 'id', operator: DEVICE_FILTERING_OPTIONS.$in.key, value: id }]));
×
162
    }
163

164
    dispatch(setDeviceListState(listState)).then(() => {
1✔
165
      if (isInitialized.current) {
1!
UNCOV
166
        return;
×
167
      }
168
      isInitialized.current = true;
1✔
169
      dispatch(setDeviceListState({}, true, true));
1✔
170
      dispatch(setOfflineThreshold());
1✔
171
    });
172
    // eslint-disable-next-line react-hooks/exhaustive-deps
173
  }, [dispatch, JSON.stringify(tenantCapabilities), JSON.stringify(locationParams), statusParam]);
174

175
  /*
176
   * Groups
177
   */
178
  const removeCurrentGroup = () => {
3✔
UNCOV
179
    const request = groupFilters.length ? dispatch(removeDynamicGroup(selectedGroup)) : dispatch(removeStaticGroup(selectedGroup));
×
UNCOV
180
    return request.then(toggleGroupRemoval).catch(console.log);
×
181
  };
182

183
  // Edit groups from device selection
184
  const addDevicesToGroup = tmpDevices => {
3✔
185
    // (save selected devices in state, open dialog)
UNCOV
186
    setTmpDevices(tmpDevices);
×
UNCOV
187
    setModifyGroupDialog(toggle);
×
188
  };
189

190
  const createGroupFromDialog = (devices, group) => {
3✔
UNCOV
191
    let request = fromFilters ? dispatch(addDynamicGroup(group, filters)) : dispatch(addStaticGroup(group, devices));
×
UNCOV
192
    return request.then(() => {
×
193
      // reached end of list
UNCOV
194
      setCreateGroupExplanation(false);
×
UNCOV
195
      setModifyGroupDialog(false);
×
UNCOV
196
      setFromFilters(false);
×
197
    });
198
  };
199

200
  const onGroupClick = () => {
3✔
UNCOV
201
    if (selectedGroup && groupFilters.length) {
×
UNCOV
202
      return dispatch(updateDynamicGroup(selectedGroup, filters));
×
203
    }
UNCOV
204
    setModifyGroupDialog(true);
×
UNCOV
205
    setFromFilters(true);
×
206
  };
207

208
  const onRemoveDevicesFromGroup = devices => {
3✔
UNCOV
209
    const isGroupRemoval = devices.length >= groupCount;
×
210
    let request;
UNCOV
211
    if (isGroupRemoval) {
×
UNCOV
212
      request = dispatch(removeStaticGroup(selectedGroup));
×
213
    } else {
UNCOV
214
      request = dispatch(removeDevicesFromGroup(selectedGroup, devices));
×
215
    }
UNCOV
216
    return request.catch(console.log);
×
217
  };
218

219
  const openSettingsDialog = e => {
3✔
UNCOV
220
    e.preventDefault();
×
UNCOV
221
    setOpenIdDialog(toggle);
×
222
  };
223

224
  const onCreateGroupClose = () => {
3✔
UNCOV
225
    setModifyGroupDialog(false);
×
UNCOV
226
    setFromFilters(false);
×
UNCOV
227
    setTmpDevices([]);
×
228
  };
229

230
  const onPreauthSaved = addMore => {
3✔
UNCOV
231
    setOpenPreauth(!addMore);
×
UNCOV
232
    dispatch(setDeviceListState({ page: 1, refreshTrigger: !refreshTrigger }));
×
233
  };
234

235
  const onShowDeviceStateClick = state => {
3✔
UNCOV
236
    dispatch(selectGroup());
×
UNCOV
237
    dispatch(setDeviceListState({ state }));
×
238
  };
239

240
  const onGroupSelect = groupName => {
3✔
UNCOV
241
    dispatch(selectGroup(groupName));
×
UNCOV
242
    dispatch(setDeviceListState({ page: 1, refreshTrigger: !refreshTrigger, selection: [] }));
×
243
  };
244

245
  const onShowAuthRequestDevicesClick = () => {
3✔
UNCOV
246
    dispatch(setDeviceFilters([]));
×
UNCOV
247
    dispatch(setDeviceListState({ selectedIssues: [DEVICE_ISSUE_OPTIONS.authRequests.key], page: 1 }));
×
248
  };
249

250
  const toggleGroupRemoval = () => setRemoveGroup(toggle);
3✔
251

252
  const toggleMakeGatewayClick = () => setShowMakeGateway(toggle);
3✔
253

254
  let onboardingComponent;
255
  if (deviceConnectionRef.current && !(pendingCount || acceptedCount)) {
3!
UNCOV
256
    const anchor = { top: deviceConnectionRef.current.offsetTop + deviceConnectionRef.current.offsetHeight / 2, left: deviceConnectionRef.current.offsetLeft };
×
UNCOV
257
    onboardingComponent = getOnboardingComponentFor(
×
258
      onboardingSteps.DEVICES_DELAYED_ONBOARDING,
259
      onboardingState,
260
      { anchor, place: 'left' },
261
      onboardingComponent
262
    );
263
  }
264
  return (
3✔
265
    <>
266
      <div className="tab-container with-sub-panels" style={{ paddingTop: 0, paddingBottom: 45, minHeight: 'max-content', alignContent: 'center' }}>
267
        <h3 className="flexbox center-aligned" style={{ marginBottom: 0, marginTop: 0, flexWrap: 'wrap' }}>
268
          Devices
269
        </h3>
270
        <span className="flexbox space-between margin-left-large margin-right center-aligned padding-top-small">
271
          {hasReporting && !!authRequestCount && (
3!
272
            <a className="flexbox center-aligned margin-right-large" onClick={onShowAuthRequestDevicesClick}>
273
              <AddIcon fontSize="small" style={{ marginRight: 6 }} />
274
              {authRequestCount} new device authentication {pluralize('request', authRequestCount)}
275
            </a>
276
          )}
277
          {!!pendingCount && !selectedGroup && selectedState !== DEVICE_STATES.pending ? (
9!
278
            <DeviceStatusNotification deviceCount={pendingCount} state={DEVICE_STATES.pending} onClick={onShowDeviceStateClick} />
279
          ) : (
280
            <div />
281
          )}
282
          {canManageDevices && (
6✔
283
            <DeviceAdditionWidget
284
              features={features}
UNCOV
285
              onConnectClick={() => dispatch(setShowConnectingDialog(true))}
×
286
              onMakeGatewayClick={toggleMakeGatewayClick}
287
              onPreauthClick={setOpenPreauth}
288
              tenantCapabilities={tenantCapabilities}
289
              innerRef={deviceConnectionRef}
290
            />
291
          )}
292
          {onboardingComponent}
293
        </span>
294
      </div>
295
      <div className="tab-container with-sub-panels" style={{ padding: 0, height: '100%' }}>
296
        <Groups
297
          className="leftFixed"
298
          acceptedCount={acceptedCount}
299
          changeGroup={onGroupSelect}
300
          groups={groupsByType}
301
          openGroupDialog={setCreateGroupExplanation}
302
          selectedGroup={selectedGroup}
303
        />
304
        <div className="rightFluid relative" style={{ paddingTop: 0 }}>
305
          {limitMaxed && <DeviceLimitWarning acceptedDevices={acceptedCount} deviceLimit={deviceLimit} />}
3!
306
          <AuthorizedDevices
307
            addDevicesToGroup={addDevicesToGroup}
308
            onGroupClick={onGroupClick}
309
            onGroupRemoval={toggleGroupRemoval}
310
            onMakeGatewayClick={toggleMakeGatewayClick}
311
            onPreauthClick={setOpenPreauth}
312
            openSettingsDialog={openSettingsDialog}
313
            removeDevicesFromGroup={onRemoveDevicesFromGroup}
314
            showsDialog={showDeviceConnectionDialog || removeGroup || modifyGroupDialog || createGroupExplanation || openIdDialog || openPreauth}
18✔
315
          />
316
        </div>
317
        {removeGroup && <RemoveGroup onClose={toggleGroupRemoval} onRemove={removeCurrentGroup} />}
3!
318
        {modifyGroupDialog && (
3!
319
          <CreateGroup
320
            addListOfDevices={createGroupFromDialog}
321
            fromFilters={fromFilters}
322
            isCreation={fromFilters || !groups.length}
×
323
            selectedDevices={tmpDevices}
324
            onClose={onCreateGroupClose}
325
          />
326
        )}
UNCOV
327
        {createGroupExplanation && <CreateGroupExplainer isEnterprise={isEnterprise} onClose={() => setCreateGroupExplanation(false)} />}
×
328
        {openIdDialog && (
3!
329
          <Dialog open>
330
            <DialogTitle>Default device identity attribute</DialogTitle>
331
            <DialogContent style={{ overflow: 'hidden' }}>
332
              <Global dialog closeDialog={openSettingsDialog} />
333
            </DialogContent>
334
          </Dialog>
335
        )}
336
        {openPreauth && (
3!
337
          <PreauthDialog
338
            acceptedDevices={acceptedCount}
339
            deviceLimit={deviceLimit}
340
            limitMaxed={limitMaxed}
341
            onSubmit={onPreauthSaved}
UNCOV
342
            onCancel={() => setOpenPreauth(false)}
×
343
          />
344
        )}
345
        {showMakeGateway && <MakeGatewayDialog isPreRelease={canPreview} onCancel={toggleMakeGatewayClick} />}
3!
346
      </div>
347
    </>
348
  );
349
};
350

351
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