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

mendersoftware / gui / 951400782

pending completion
951400782

Pull #3900

gitlab-ci

web-flow
chore: bump @testing-library/jest-dom from 5.16.5 to 5.17.0

Bumps [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) from 5.16.5 to 5.17.0.
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v5.16.5...v5.17.0)

---
updated-dependencies:
- dependency-name: "@testing-library/jest-dom"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #3900: chore: bump @testing-library/jest-dom from 5.16.5 to 5.17.0

4446 of 6414 branches covered (69.32%)

8342 of 10084 relevant lines covered (82.73%)

186.0 hits per line

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

84.38
/src/js/actions/deviceActions.js
1
/*eslint import/namespace: ['error', { allowComputed: true }]*/
2
import React from 'react';
3
import { Link } from 'react-router-dom';
4

5
import { isCancel } from 'axios';
6
import pluralize from 'pluralize';
7
import { v4 as uuid } from 'uuid';
8

9
import { commonErrorFallback, commonErrorHandler, setSnackbar } from '../actions/appActions';
10
import { getSingleDeployment } from '../actions/deploymentActions';
11
import { auditLogsApiUrl } from '../actions/organizationActions';
12
import { cleanUpUpload, progress } from '../actions/releaseActions';
13
import { saveGlobalSettings } from '../actions/userActions';
14
import GeneralApi, { MAX_PAGE_SIZE, apiUrl, headerNames } from '../api/general-api';
15
import { routes, sortingAlternatives } from '../components/devices/base-devices';
16
import { SORTING_OPTIONS, TIMEOUTS, UPLOAD_PROGRESS, emptyChartSelection, yes } from '../constants/appConstants';
17
import * as DeviceConstants from '../constants/deviceConstants';
18
import { rootfsImageVersion } from '../constants/releaseConstants';
19
import { attributeDuplicateFilter, deepCompare, extractErrorMessage, getSnackbarMessage, mapDeviceAttributes } from '../helpers';
20
import {
21
  getDeviceById as getDeviceByIdSelector,
22
  getDeviceFilters,
23
  getDeviceTwinIntegrations,
24
  getGroups as getGroupsSelector,
25
  getIdAttribute,
26
  getTenantCapabilities,
27
  getUserCapabilities,
28
  getUserSettings
29
} from '../selectors';
30
import { chartColorPalette } from '../themes/Mender';
31
import { getDeviceMonitorConfig, getLatestDeviceAlerts } from './monitorActions';
32

33
const { DEVICE_FILTERING_OPTIONS, DEVICE_STATES, DEVICE_LIST_DEFAULTS, UNGROUPED_GROUP, emptyFilter } = DeviceConstants;
187✔
34
const { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
187✔
35

36
export const deviceAuthV2 = `${apiUrl.v2}/devauth`;
187✔
37
export const deviceConnect = `${apiUrl.v1}/deviceconnect`;
187✔
38
export const inventoryApiUrl = `${apiUrl.v1}/inventory`;
187✔
39
export const inventoryApiUrlV2 = `${apiUrl.v2}/inventory`;
187✔
40
export const deviceConfig = `${apiUrl.v1}/deviceconfig/configurations/device`;
187✔
41
export const reportingApiUrl = `${apiUrl.v1}/reporting`;
187✔
42
export const iotManagerBaseURL = `${apiUrl.v1}/iot-manager`;
187✔
43

44
const defaultAttributes = [
187✔
45
  { scope: 'identity', attribute: 'status' },
46
  { scope: 'inventory', attribute: 'artifact_name' },
47
  { scope: 'inventory', attribute: 'device_type' },
48
  { scope: 'inventory', attribute: 'mender_is_gateway' },
49
  { scope: 'inventory', attribute: 'mender_gateway_system_id' },
50
  { scope: 'inventory', attribute: rootfsImageVersion },
51
  { scope: 'monitor', attribute: 'alerts' },
52
  { scope: 'system', attribute: 'created_ts' },
53
  { scope: 'system', attribute: 'updated_ts' },
54
  { scope: 'system', attribute: 'check_in_time' },
55
  { scope: 'system', attribute: 'group' },
56
  { scope: 'tags', attribute: 'name' }
57
];
58

59
export const getSearchEndpoint = hasReporting => (hasReporting ? `${reportingApiUrl}/devices/search` : `${inventoryApiUrlV2}/filters/search`);
489!
60

61
const getAttrsEndpoint = hasReporting => (hasReporting ? `${reportingApiUrl}/devices/search/attributes` : `${inventoryApiUrlV2}/filters/attributes`);
187✔
62

63
export const getGroups = () => (dispatch, getState) =>
187✔
64
  GeneralApi.get(`${inventoryApiUrl}/groups`).then(res => {
27✔
65
    const state = getState().devices.groups.byId;
27✔
66
    const dynamicGroups = Object.entries(state).reduce((accu, [id, group]) => {
27✔
67
      if (group.id || (group.filters?.length && id !== UNGROUPED_GROUP.id)) {
52✔
68
        accu[id] = group;
25✔
69
      }
70
      return accu;
52✔
71
    }, {});
72
    const groups = res.data.reduce((accu, group) => {
27✔
73
      accu[group] = { deviceIds: [], filters: [], total: 0, ...state[group] };
27✔
74
      return accu;
27✔
75
    }, dynamicGroups);
76
    const filters = [{ key: 'group', value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: 'system' }];
27✔
77
    return Promise.all([
27✔
78
      dispatch({ type: DeviceConstants.RECEIVE_GROUPS, groups }),
79
      dispatch(getDevicesByStatus(undefined, { filterSelection: filters, group: 0, page: 1, perPage: 1 }))
80
    ]).then(promises => {
81
      const ungroupedDevices = promises[promises.length - 1] || [];
27!
82
      const result = ungroupedDevices[ungroupedDevices.length - 1] || {};
27!
83
      if (!result.total) {
27!
84
        return Promise.resolve();
×
85
      }
86
      return Promise.resolve(
27✔
87
        dispatch({
88
          type: DeviceConstants.ADD_DYNAMIC_GROUP,
89
          groupName: UNGROUPED_GROUP.id,
90
          group: {
91
            deviceIds: [],
92
            total: 0,
93
            ...getState().devices.groups.byId[UNGROUPED_GROUP.id],
94
            filters: [{ key: 'group', value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: 'system' }]
95
          }
96
        })
97
      );
98
    });
99
  });
100

101
export const addDevicesToGroup = (group, deviceIds, isCreation) => dispatch =>
187✔
102
  GeneralApi.patch(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds)
2✔
103
    .then(() => dispatch({ type: DeviceConstants.ADD_TO_GROUP, group, deviceIds }))
2✔
104
    .finally(() => (isCreation ? Promise.resolve(dispatch(getGroups())) : {}));
2✔
105

106
export const removeDevicesFromGroup = (group, deviceIds) => dispatch =>
187✔
107
  GeneralApi.delete(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(() =>
1✔
108
    Promise.all([
1✔
109
      dispatch({
110
        type: DeviceConstants.REMOVE_FROM_GROUP,
111
        group,
112
        deviceIds
113
      }),
114
      dispatch(setSnackbar(`The ${pluralize('devices', deviceIds.length)} ${pluralize('were', deviceIds.length)} removed from the group`, TIMEOUTS.fiveSeconds))
115
    ])
116
  );
117

118
const getGroupNotification = (newGroup, selectedGroup) => {
187✔
119
  const successMessage = 'The group was updated successfully';
3✔
120
  if (newGroup === selectedGroup) {
3✔
121
    return [successMessage, TIMEOUTS.fiveSeconds];
1✔
122
  }
123
  return [
2✔
124
    <>
125
      {successMessage} - <Link to={`/devices?inventory=group:eq:${newGroup}`}>click here</Link> to see it.
126
    </>,
127
    5000,
128
    undefined,
129
    undefined,
130
    () => {}
131
  ];
132
};
133

134
export const addStaticGroup = (group, devices) => (dispatch, getState) =>
187✔
135
  Promise.resolve(
1✔
136
    dispatch(
137
      addDevicesToGroup(
138
        group,
139
        devices.map(({ id }) => id),
1✔
140
        true
141
      )
142
    )
143
  )
144
    .then(() =>
145
      Promise.resolve(
1✔
146
        dispatch({
147
          type: DeviceConstants.ADD_STATIC_GROUP,
148
          group: { deviceIds: [], total: 0, filters: [], ...getState().devices.groups.byId[group] },
149
          groupName: group
150
        })
151
      ).then(() =>
152
        Promise.all([
1✔
153
          dispatch(setDeviceListState({ selectedId: undefined, setOnly: true })),
154
          dispatch(getGroups()),
155
          dispatch(setSnackbar(...getGroupNotification(group, getState().devices.groups.selectedGroup)))
156
        ])
157
      )
158
    )
159
    .catch(err => commonErrorHandler(err, `Group could not be updated:`, dispatch));
×
160

161
export const removeStaticGroup = groupName => (dispatch, getState) => {
187✔
162
  return GeneralApi.delete(`${inventoryApiUrl}/groups/${groupName}`).then(() => {
1✔
163
    const selectedGroup = getState().devices.groups.selectedGroup === groupName ? undefined : getState().devices.groups.selectedGroup;
1!
164
    // eslint-disable-next-line no-unused-vars
165
    const { [groupName]: removal, ...groups } = getState().devices.groups.byId;
1✔
166
    return Promise.all([
1✔
167
      dispatch({
168
        type: DeviceConstants.REMOVE_STATIC_GROUP,
169
        groups
170
      }),
171
      dispatch(getGroups()),
172
      dispatch(selectGroup(selectedGroup)),
173
      dispatch(setSnackbar('Group was removed successfully', TIMEOUTS.fiveSeconds))
174
    ]);
175
  });
176
};
177

178
// for some reason these functions can not be stored in the deviceConstants...
179
const filterProcessors = {
187✔
180
  $gt: val => Number(val) || val,
×
181
  $gte: val => Number(val) || val,
×
182
  $lt: val => Number(val) || val,
6✔
183
  $lte: val => Number(val) || val,
×
184
  $in: val => ('' + val).split(',').map(i => i.trim()),
×
185
  $nin: val => ('' + val).split(',').map(i => i.trim()),
28✔
186
  $exists: yes,
187
  $nexists: () => false
×
188
};
189
const filterAliases = {
187✔
190
  $nexists: { alias: DEVICE_FILTERING_OPTIONS.$exists.key, value: false }
191
};
192
const mapFiltersToTerms = filters =>
187✔
193
  filters.map(filter => ({
501✔
194
    scope: filter.scope,
195
    attribute: filter.key,
196
    type: filterAliases[filter.operator]?.alias || filter.operator,
1,002✔
197
    value: filterProcessors.hasOwnProperty(filter.operator) ? filterProcessors[filter.operator](filter.value) : filter.value
501✔
198
  }));
199
const mapTermsToFilters = terms =>
187✔
200
  terms.map(term => {
22✔
201
    const aliasedFilter = Object.entries(filterAliases).find(
66✔
202
      aliasDefinition => aliasDefinition[1].alias === term.type && aliasDefinition[1].value === term.value
66✔
203
    );
204
    const operator = aliasedFilter ? aliasedFilter[0] : term.type;
66✔
205
    return { scope: term.scope, key: term.attribute, operator, value: term.value };
66✔
206
  });
207

208
export const getDynamicGroups = () => (dispatch, getState) =>
187✔
209
  GeneralApi.get(`${inventoryApiUrlV2}/filters?per_page=${MAX_PAGE_SIZE}`)
22✔
210
    .then(({ data: filters }) => {
211
      const state = getState().devices.groups.byId;
22✔
212
      const staticGroups = Object.entries(state).reduce((accu, [id, group]) => {
22✔
213
        if (!(group.id || group.filters?.length)) {
42✔
214
          accu[id] = group;
22✔
215
        }
216
        return accu;
42✔
217
      }, {});
218
      const groups = (filters || []).reduce((accu, filter) => {
22!
219
        accu[filter.name] = {
22✔
220
          deviceIds: [],
221
          total: 0,
222
          ...state[filter.name],
223
          id: filter.id,
224
          filters: mapTermsToFilters(filter.terms)
225
        };
226
        return accu;
22✔
227
      }, staticGroups);
228
      return Promise.resolve(dispatch({ type: DeviceConstants.RECEIVE_DYNAMIC_GROUPS, groups }));
22✔
229
    })
230
    .catch(() => console.log('Dynamic group retrieval failed - likely accessing a non-enterprise backend'));
×
231

232
export const addDynamicGroup = (groupName, filterPredicates) => (dispatch, getState) =>
187✔
233
  GeneralApi.post(`${inventoryApiUrlV2}/filters`, { name: groupName, terms: mapFiltersToTerms(filterPredicates) })
2✔
234
    .then(res =>
235
      Promise.resolve(
2✔
236
        dispatch({
237
          type: DeviceConstants.ADD_DYNAMIC_GROUP,
238
          groupName,
239
          group: {
240
            deviceIds: [],
241
            total: 0,
242
            ...getState().devices.groups.byId[groupName],
243
            id: res.headers[headerNames.location].substring(res.headers[headerNames.location].lastIndexOf('/') + 1),
244
            filters: filterPredicates
245
          }
246
        })
247
      ).then(() => {
248
        const { cleanedFilters } = getGroupFilters(groupName, getState().devices.groups);
2✔
249
        return Promise.all([
2✔
250
          dispatch(setDeviceFilters(cleanedFilters)),
251
          dispatch(setSnackbar(...getGroupNotification(groupName, getState().devices.groups.selectedGroup))),
252
          dispatch(getDynamicGroups())
253
        ]);
254
      })
255
    )
256
    .catch(err => commonErrorHandler(err, `Group could not be updated:`, dispatch));
×
257

258
export const updateDynamicGroup = (groupName, filterPredicates) => (dispatch, getState) => {
187✔
259
  const filterId = getState().devices.groups.byId[groupName].id;
1✔
260
  return GeneralApi.delete(`${inventoryApiUrlV2}/filters/${filterId}`).then(() => Promise.resolve(dispatch(addDynamicGroup(groupName, filterPredicates))));
1✔
261
};
262

263
export const removeDynamicGroup = groupName => (dispatch, getState) => {
187✔
264
  let groups = { ...getState().devices.groups.byId };
1✔
265
  const filterId = groups[groupName].id;
1✔
266
  const selectedGroup = getState().devices.groups.selectedGroup === groupName ? undefined : getState().devices.groups.selectedGroup;
1!
267
  return Promise.all([GeneralApi.delete(`${inventoryApiUrlV2}/filters/${filterId}`), dispatch(selectGroup(selectedGroup))]).then(() => {
1✔
268
    delete groups[groupName];
1✔
269
    return Promise.all([
1✔
270
      dispatch({
271
        type: DeviceConstants.REMOVE_DYNAMIC_GROUP,
272
        groups
273
      }),
274
      dispatch(setSnackbar('Group was removed successfully', TIMEOUTS.fiveSeconds))
275
    ]);
276
  });
277
};
278
/*
279
 * Device inventory functions
280
 */
281
const getGroupFilters = (group, groupsState, filters = []) => {
187✔
282
  const groupName = group === UNGROUPED_GROUP.id || group === UNGROUPED_GROUP.name ? UNGROUPED_GROUP.id : group;
11!
283
  const selectedGroup = groupsState.byId[groupName];
11✔
284
  const groupFilterLength = selectedGroup?.filters?.length || 0;
11✔
285
  const cleanedFilters = groupFilterLength
11✔
286
    ? (filters.length ? filters : selectedGroup.filters).filter((item, index, array) => array.findIndex(filter => deepCompare(filter, item)) == index)
5✔
287
    : filters;
288
  return { cleanedFilters, groupName, selectedGroup, groupFilterLength };
11✔
289
};
290

291
export const selectGroup =
292
  (group, filters = []) =>
187✔
293
  (dispatch, getState) => {
5✔
294
    const { cleanedFilters, groupName, selectedGroup, groupFilterLength } = getGroupFilters(group, getState().devices.groups, filters);
5✔
295
    const state = getState();
5✔
296
    if (state.devices.groups.selectedGroup === groupName && filters.length === 0 && !groupFilterLength) {
5✔
297
      return;
2✔
298
    }
299
    let tasks = [];
3✔
300
    if (groupFilterLength) {
3✔
301
      tasks.push(dispatch(setDeviceFilters(cleanedFilters)));
2✔
302
    } else {
303
      tasks.push(dispatch(setDeviceFilters(filters)));
1✔
304
      tasks.push(dispatch(getGroupDevices(groupName, { perPage: 1, shouldIncludeAllStates: true })));
1✔
305
    }
306
    const selectedGroupName = selectedGroup || !Object.keys(state.devices.groups.byId).length ? groupName : undefined;
3!
307
    tasks.push(dispatch({ type: DeviceConstants.SELECT_GROUP, group: selectedGroupName }));
3✔
308
    return Promise.all(tasks);
3✔
309
  };
310
const getEarliestTs = (dateA = '', dateB = '') => (!dateA || !dateB ? dateA || dateB : dateA < dateB ? dateA : dateB);
282!
311
const getLatestTs = (dateA = '', dateB = '') => (!dateA || !dateB ? dateA || dateB : dateA >= dateB ? dateA : dateB);
423✔
312

313
const reduceReceivedDevices = (devices, ids, state, status) =>
187✔
314
  devices.reduce(
137✔
315
    (accu, device) => {
316
      const stateDevice = getDeviceByIdSelector(state, device.id);
141✔
317
      const {
318
        attributes: storedAttributes = {},
2✔
319
        identity_data: storedIdentity = {},
2✔
320
        monitor: storedMonitor = {},
102✔
321
        tags: storedTags = {},
102✔
322
        group: storedGroup
323
      } = stateDevice;
141✔
324
      const { identity, inventory, monitor, system = {}, tags } = mapDeviceAttributes(device.attributes);
141!
325
      // all the other mapped attributes return as empty objects if there are no attributes to map, but identity will be initialized with an empty state
326
      // for device_type and artifact_name, potentially overwriting existing info, so rely on stored information instead if there are no attributes
327
      device.attributes = device.attributes ? { ...storedAttributes, ...inventory } : storedAttributes;
141✔
328
      device.tags = { ...storedTags, ...tags };
141✔
329
      device.group = system.group ?? storedGroup;
141✔
330
      device.monitor = { ...storedMonitor, ...monitor };
141✔
331
      device.identity_data = { ...storedIdentity, ...identity, ...(device.identity_data ? device.identity_data : {}) };
141✔
332
      device.status = status ? status : device.status || identity.status;
141✔
333
      device.created_ts = getEarliestTs(getEarliestTs(system.created_ts, device.created_ts), stateDevice.created_ts);
141✔
334
      device.updated_ts = getLatestTs(getLatestTs(getLatestTs(device.check_in_time, device.updated_ts), system.updated_ts), stateDevice.updated_ts);
141✔
335
      device.isNew = new Date(device.created_ts) > new Date(state.app.newThreshold);
141✔
336
      device.isOffline = new Date(device.updated_ts) < new Date(state.app.offlineThreshold);
141✔
337
      accu.devicesById[device.id] = { ...stateDevice, ...device };
141✔
338
      accu.ids.push(device.id);
141✔
339
      return accu;
141✔
340
    },
341
    { ids, devicesById: {} }
342
  );
343

344
export const getGroupDevices =
345
  (group, options = {}) =>
187✔
346
  (dispatch, getState) => {
4✔
347
    const { shouldIncludeAllStates, ...remainder } = options;
4✔
348
    const { cleanedFilters: filterSelection } = getGroupFilters(group, getState().devices.groups);
4✔
349
    return Promise.resolve(
4✔
350
      dispatch(getDevicesByStatus(shouldIncludeAllStates ? undefined : DEVICE_STATES.accepted, { ...remainder, filterSelection, group }))
4✔
351
    ).then(results => {
352
      if (!group) {
4✔
353
        return Promise.resolve();
1✔
354
      }
355
      const { deviceAccu, total } = results[results.length - 1];
3✔
356
      const stateGroup = getState().devices.groups.byId[group];
3✔
357
      if (!stateGroup && !total && !deviceAccu.ids.length) {
3✔
358
        return Promise.resolve();
1✔
359
      }
360
      return Promise.resolve(
2✔
361
        dispatch({
362
          type: DeviceConstants.RECEIVE_GROUP_DEVICES,
363
          group: {
364
            filters: [],
365
            ...stateGroup,
366
            deviceIds: deviceAccu.ids.length === total || deviceAccu.ids.length > stateGroup?.deviceIds ? deviceAccu.ids : stateGroup.deviceIds,
6!
367
            total
368
          },
369
          groupName: group
370
        })
371
      );
372
    });
373
  };
374

375
export const getAllGroupDevices = (group, shouldIncludeAllStates) => (dispatch, getState) => {
187✔
376
  if (!group || (!!group && (!getState().devices.groups.byId[group] || getState().devices.groups.byId[group].filters.length))) {
13✔
377
    return Promise.resolve();
12✔
378
  }
379
  const { attributes, filterTerms } = prepareSearchArguments({
1✔
380
    filters: [],
381
    group,
382
    state: getState(),
383
    status: shouldIncludeAllStates ? undefined : DEVICE_STATES.accepted
1!
384
  });
385
  const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage, devices = []) =>
1✔
386
    GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
1✔
387
      page,
388
      per_page: perPage,
389
      filters: filterTerms,
390
      attributes
391
    }).then(res => {
392
      const state = getState();
1✔
393
      const deviceAccu = reduceReceivedDevices(res.data, devices, state);
1✔
394
      dispatch({
1✔
395
        type: DeviceConstants.RECEIVE_DEVICES,
396
        devicesById: deviceAccu.devicesById
397
      });
398
      const total = Number(res.headers[headerNames.total]);
1✔
399
      if (total > perPage * page) {
1!
400
        return getAllDevices(perPage, page + 1, deviceAccu.ids);
×
401
      }
402
      return Promise.resolve(
1✔
403
        dispatch({
404
          type: DeviceConstants.RECEIVE_GROUP_DEVICES,
405
          group: {
406
            filters: [],
407
            ...state.devices.groups.byId[group],
408
            deviceIds: deviceAccu.ids,
409
            total: deviceAccu.ids.length
410
          },
411
          groupName: group
412
        })
413
      );
414
    });
415
  return getAllDevices();
1✔
416
};
417

418
export const getAllDynamicGroupDevices = group => (dispatch, getState) => {
187✔
419
  if (!!group && (!getState().devices.groups.byId[group] || !getState().devices.groups.byId[group].filters.length)) {
13✔
420
    return Promise.resolve();
12✔
421
  }
422
  const { attributes, filterTerms: filters } = prepareSearchArguments({
1✔
423
    filters: getState().devices.groups.byId[group].filters,
424
    state: getState(),
425
    status: DEVICE_STATES.accepted
426
  });
427
  const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage, devices = []) =>
1✔
428
    GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), { page, per_page: perPage, filters, attributes }).then(res => {
1✔
429
      const state = getState();
1✔
430
      const deviceAccu = reduceReceivedDevices(res.data, devices, state);
1✔
431
      dispatch({
1✔
432
        type: DeviceConstants.RECEIVE_DEVICES,
433
        devicesById: deviceAccu.devicesById
434
      });
435
      const total = Number(res.headers[headerNames.total]);
1✔
436
      if (total > deviceAccu.ids.length) {
1!
437
        return getAllDevices(perPage, page + 1, deviceAccu.ids);
×
438
      }
439
      return Promise.resolve(
1✔
440
        dispatch({
441
          type: DeviceConstants.RECEIVE_GROUP_DEVICES,
442
          group: {
443
            ...state.devices.groups.byId[group],
444
            deviceIds: deviceAccu.ids,
445
            total
446
          },
447
          groupName: group
448
        })
449
      );
450
    });
451
  return getAllDevices();
1✔
452
};
453

454
export const setDeviceFilters = filters => (dispatch, getState) => {
187✔
455
  if (deepCompare(filters, getDeviceFilters(getState()))) {
6✔
456
    return Promise.resolve();
2✔
457
  }
458
  return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_FILTERS, filters }));
4✔
459
};
460

461
export const getDeviceById = id => (dispatch, getState) =>
187✔
462
  GeneralApi.get(`${inventoryApiUrl}/devices/${id}`)
6✔
463
    .then(res => {
464
      const device = reduceReceivedDevices([res.data], [], getState()).devicesById[id];
5✔
465
      device.etag = res.headers.etag;
5✔
466
      dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device });
5✔
467
      return Promise.resolve(device);
5✔
468
    })
469
    .catch(err => {
470
      const errMsg = extractErrorMessage(err);
×
471
      if (errMsg.includes('Not Found')) {
×
472
        console.log(`${id} does not have any inventory information`);
×
473
        const device = reduceReceivedDevices(
×
474
          [
475
            {
476
              id,
477
              attributes: [
478
                { name: 'status', value: 'decomissioned', scope: 'identity' },
479
                { name: 'decomissioned', value: 'true', scope: 'inventory' }
480
              ]
481
            }
482
          ],
483
          [],
484
          getState()
485
        ).devicesById[id];
486
        dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device });
×
487
      }
488
    });
489

490
export const getDeviceInfo = deviceId => (dispatch, getState) => {
187✔
491
  const device = getState().devices.byId[deviceId] || {};
2!
492
  const { hasDeviceConfig, hasDeviceConnect, hasMonitor } = getTenantCapabilities(getState());
2✔
493
  const { canConfigure } = getUserCapabilities(getState());
2✔
494
  const integrations = getDeviceTwinIntegrations(getState());
2✔
495
  let tasks = [dispatch(getDeviceAuth(deviceId)), ...integrations.map(integration => dispatch(getDeviceTwin(deviceId, integration)))];
2✔
496
  if (hasDeviceConfig && canConfigure && [DEVICE_STATES.accepted, DEVICE_STATES.preauth].includes(device.status)) {
2✔
497
    tasks.push(dispatch(getDeviceConfig(deviceId)));
1✔
498
  }
499
  if (device.status === DEVICE_STATES.accepted) {
2!
500
    // Get full device identity details for single selected device
501
    tasks.push(dispatch(getDeviceById(deviceId)));
2✔
502
    if (hasDeviceConnect) {
2!
503
      tasks.push(dispatch(getDeviceConnect(deviceId)));
2✔
504
    }
505
    if (hasMonitor) {
2✔
506
      tasks.push(dispatch(getLatestDeviceAlerts(deviceId)));
1✔
507
      tasks.push(dispatch(getDeviceMonitorConfig(deviceId)));
1✔
508
    }
509
  }
510
  return Promise.all(tasks);
2✔
511
};
512

513
const deriveInactiveDevices = deviceIds => (dispatch, getState) => {
187✔
514
  const yesterday = new Date();
1✔
515
  yesterday.setDate(yesterday.getDate() - 1);
1✔
516
  const yesterdaysIsoString = yesterday.toISOString();
1✔
517
  const state = getState().devices;
1✔
518
  // now boil the list down to the ones that were not updated since yesterday
519
  const devices = deviceIds.reduce(
1✔
520
    (accu, id) => {
521
      const device = state.byId[id];
2✔
522
      if (device && device.updated_ts > yesterdaysIsoString) {
2!
523
        accu.active.push(id);
×
524
      } else {
525
        accu.inactive.push(id);
2✔
526
      }
527
      return accu;
2✔
528
    },
529
    { active: [], inactive: [] }
530
  );
531
  return dispatch({
1✔
532
    type: DeviceConstants.SET_INACTIVE_DEVICES,
533
    activeDeviceTotal: devices.active.length,
534
    inactiveDeviceTotal: devices.inactive.length
535
  });
536
};
537

538
/*
539
    Device Auth + admission
540
  */
541
export const getDeviceCount = status => (dispatch, getState) =>
402✔
542
  GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
402✔
543
    page: 1,
544
    per_page: 1,
545
    filters: mapFiltersToTerms([{ key: 'status', value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'identity' }]),
546
    attributes: defaultAttributes
547
  }).then(response => {
548
    const count = Number(response.headers[headerNames.total]);
398✔
549
    switch (status) {
398!
550
      case DEVICE_STATES.accepted:
551
      case DEVICE_STATES.pending:
552
      case DEVICE_STATES.preauth:
553
      case DEVICE_STATES.rejected:
554
        return dispatch({ type: DeviceConstants[`SET_${status.toUpperCase()}_DEVICES_COUNT`], count, status });
398✔
555
      default:
556
        return dispatch({ type: DeviceConstants.SET_TOTAL_DEVICES, count });
×
557
    }
558
  });
559

560
export const getAllDeviceCounts = () => dispatch =>
187✔
561
  Promise.all([DEVICE_STATES.accepted, DEVICE_STATES.pending].map(status => dispatch(getDeviceCount(status))));
362✔
562

563
export const getDeviceLimit = () => dispatch =>
187✔
564
  GeneralApi.get(`${deviceAuthV2}/limits/max_devices`).then(res =>
6✔
565
    dispatch({
6✔
566
      type: DeviceConstants.SET_DEVICE_LIMIT,
567
      limit: res.data.limit
568
    })
569
  );
570

571
export const setDeviceListState =
572
  (selectionState, shouldSelectDevices = true) =>
187✔
573
  (dispatch, getState) => {
17✔
574
    const currentState = getState().devices.deviceList;
17✔
575
    let nextState = {
17✔
576
      ...currentState,
577
      setOnly: false,
578
      ...selectionState,
579
      sort: { ...currentState.sort, ...selectionState.sort }
580
    };
581
    let tasks = [];
17✔
582
    // eslint-disable-next-line no-unused-vars
583
    const { isLoading: currentLoading, deviceIds: currentDevices, selection: currentSelection, ...currentRequestState } = currentState;
17✔
584
    // eslint-disable-next-line no-unused-vars
585
    const { isLoading: nextLoading, deviceIds: nextDevices, selection: nextSelection, ...nextRequestState } = nextState;
17✔
586
    if (!nextState.setOnly && !deepCompare(currentRequestState, nextRequestState)) {
17✔
587
      const { direction: sortDown = SORTING_OPTIONS.desc, key: sortCol, scope: sortScope } = nextState.sort ?? {};
13!
588
      const sortBy = sortCol ? [{ attribute: sortCol, order: sortDown, scope: sortScope }] : undefined;
13!
589
      if (sortCol && sortingAlternatives[sortCol]) {
13!
590
        sortBy.push({ ...sortBy[0], attribute: sortingAlternatives[sortCol] });
×
591
      }
592
      const applicableSelectedState = nextState.state === routes.allDevices.key ? undefined : nextState.state;
13!
593
      nextState.isLoading = true;
13✔
594
      tasks.push(
13✔
595
        dispatch(getDevicesByStatus(applicableSelectedState, { ...nextState, sortOptions: sortBy }))
596
          .then(results => {
597
            const { deviceAccu, total } = results[results.length - 1];
11✔
598
            const devicesState = shouldSelectDevices
11!
599
              ? { ...getState().devices.deviceList, deviceIds: deviceAccu.ids, total, isLoading: false }
600
              : { ...getState().devices.deviceList, isLoading: false };
601
            return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_LIST_STATE, state: devicesState }));
11✔
602
          })
603
          // whatever happens, change "loading" back to null
604
          .catch(() =>
605
            Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_LIST_STATE, state: { ...getState().devices.deviceList, isLoading: false } }))
×
606
          )
607
      );
608
    }
609
    tasks.push(dispatch({ type: DeviceConstants.SET_DEVICE_LIST_STATE, state: nextState }));
17✔
610
    return Promise.all(tasks);
17✔
611
  };
612

613
const convertIssueOptionsToFilters = (issuesSelection, filtersState = {}) =>
187!
614
  issuesSelection.map(item => {
84✔
615
    if (typeof DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule.value === 'function') {
13✔
616
      return { ...DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule, value: DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule.value(filtersState) };
6✔
617
    }
618
    return DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule;
7✔
619
  });
620

621
export const convertDeviceListStateToFilters = ({ filters = [], group, groups = { byId: {} }, offlineThreshold, selectedIssues = [], status }) => {
187!
622
  let applicableFilters = [...filters];
84✔
623
  if (typeof group === 'string' && !(groups.byId[group]?.filters || applicableFilters).length) {
84✔
624
    applicableFilters.push({ key: 'group', value: group, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'system' });
5✔
625
  }
626
  const nonMonitorFilters = applicableFilters.filter(
84✔
627
    filter =>
628
      !Object.values(DeviceConstants.DEVICE_ISSUE_OPTIONS).some(
41✔
629
        ({ filterRule }) => filter.scope !== 'inventory' && filterRule.scope === filter.scope && filterRule.key === filter.key
246✔
630
      )
631
  );
632
  const deviceIssueFilters = convertIssueOptionsToFilters(selectedIssues, { offlineThreshold });
84✔
633
  applicableFilters = [...nonMonitorFilters, ...deviceIssueFilters];
84✔
634
  const effectiveFilters = status
84✔
635
    ? [...applicableFilters, { key: 'status', value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'identity' }]
636
    : applicableFilters;
637
  return { applicableFilters: nonMonitorFilters, filterTerms: mapFiltersToTerms(effectiveFilters) };
84✔
638
};
639

640
// get devices from inventory
641
export const getDevicesByStatus =
642
  (status, options = {}) =>
187✔
643
  (dispatch, getState) => {
68✔
644
    const { filterSelection, group, selectedIssues = [], page = defaultPage, perPage = defaultPerPage, sortOptions = [], selectedAttributes = [] } = options;
68✔
645
    const { applicableFilters, filterTerms } = convertDeviceListStateToFilters({
68✔
646
      filters: filterSelection ?? getDeviceFilters(getState()),
105✔
647
      group: group ?? getState().devices.groups.selectedGroup,
106✔
648
      groups: getState().devices.groups,
649
      offlineThreshold: getState().app.offlineThreshold,
650
      selectedIssues,
651
      status
652
    });
653
    const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(getState()).attribute || 'id' }, ...selectedAttributes];
68!
654
    return GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
68✔
655
      page,
656
      per_page: perPage,
657
      filters: filterTerms,
658
      sort: sortOptions,
659
      attributes
660
    })
661
      .then(response => {
662
        const state = getState();
66✔
663
        const deviceAccu = reduceReceivedDevices(response.data, [], state, status);
66✔
664
        let total = !applicableFilters.length ? Number(response.headers[headerNames.total]) : null;
66✔
665
        if (status && state.devices.byStatus[status].total === deviceAccu.ids.length) {
66✔
666
          total = deviceAccu.ids.length;
33✔
667
        }
668
        let tasks = [
66✔
669
          dispatch({
670
            type: DeviceConstants.RECEIVE_DEVICES,
671
            devicesById: deviceAccu.devicesById
672
          })
673
        ];
674
        if (status) {
66✔
675
          tasks.push(
38✔
676
            dispatch({
677
              type: DeviceConstants[`SET_${status.toUpperCase()}_DEVICES`],
678
              deviceIds: deviceAccu.ids,
679
              status,
680
              total
681
            })
682
          );
683
        }
684
        // for each device, get device identity info
685
        const receivedDevices = Object.values(deviceAccu.devicesById);
66✔
686
        if (receivedDevices.length) {
66✔
687
          tasks.push(dispatch(getDevicesWithAuth(receivedDevices)));
55✔
688
        }
689
        tasks.push(Promise.resolve({ deviceAccu, total: Number(response.headers[headerNames.total]) }));
66✔
690
        return Promise.all(tasks);
66✔
691
      })
692
      .catch(err => commonErrorHandler(err, `${status} devices couldn't be loaded.`, dispatch, commonErrorFallback));
×
693
  };
694

695
export const getAllDevicesByStatus = status => (dispatch, getState) => {
187✔
696
  const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(getState()).attribute || 'id' }];
1!
697
  const getAllDevices = (perPage = MAX_PAGE_SIZE, page = 1, devices = []) =>
1✔
698
    GeneralApi.post(getSearchEndpoint(getState().app.features.hasReporting), {
1✔
699
      page,
700
      per_page: perPage,
701
      filters: mapFiltersToTerms([{ key: 'status', value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: 'identity' }]),
702
      attributes
703
    }).then(res => {
704
      const state = getState();
1✔
705
      const deviceAccu = reduceReceivedDevices(res.data, devices, state, status);
1✔
706
      dispatch({
1✔
707
        type: DeviceConstants.RECEIVE_DEVICES,
708
        devicesById: deviceAccu.devicesById
709
      });
710
      const total = Number(res.headers[headerNames.total]);
1✔
711
      if (total > state.deployments.deploymentDeviceLimit) {
1!
712
        return Promise.resolve();
×
713
      }
714
      if (total > perPage * page) {
1!
715
        return getAllDevices(perPage, page + 1, deviceAccu.ids);
×
716
      }
717
      let tasks = [
1✔
718
        dispatch({
719
          type: DeviceConstants[`SET_${status.toUpperCase()}_DEVICES`],
720
          deviceIds: deviceAccu.ids,
721
          forceUpdate: true,
722
          status,
723
          total: deviceAccu.ids.length
724
        })
725
      ];
726
      if (status === DEVICE_STATES.accepted && deviceAccu.ids.length === total) {
1!
727
        tasks.push(dispatch(deriveInactiveDevices(deviceAccu.ids)));
1✔
728
      }
729
      return Promise.all(tasks);
1✔
730
    });
731
  return getAllDevices();
1✔
732
};
733

734
export const searchDevices =
735
  (passedOptions = {}) =>
187!
736
  (dispatch, getState) => {
2✔
737
    const state = getState();
2✔
738
    let options = { ...state.app.searchState, ...passedOptions };
2✔
739
    const { page = defaultPage, searchTerm, sortOptions = [] } = options;
2✔
740
    const { columnSelection = [] } = getUserSettings(state);
2!
741
    const selectedAttributes = columnSelection.map(column => ({ attribute: column.key, scope: column.scope }));
2✔
742
    const attributes = attributeDuplicateFilter(
2✔
743
      [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(state).attribute }, ...selectedAttributes],
744
      'attribute'
745
    );
746
    return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
2✔
747
      page,
748
      per_page: 10,
749
      filters: [],
750
      sort: sortOptions,
751
      text: searchTerm,
752
      attributes
753
    })
754
      .then(response => {
755
        const deviceAccu = reduceReceivedDevices(response.data, [], getState());
2✔
756
        return Promise.all([
2✔
757
          dispatch({ type: DeviceConstants.RECEIVE_DEVICES, devicesById: deviceAccu.devicesById }),
758
          Promise.resolve({ deviceIds: deviceAccu.ids, searchTotal: Number(response.headers[headerNames.total]) })
759
        ]);
760
      })
761
      .catch(err => commonErrorHandler(err, `devices couldn't be searched.`, dispatch, commonErrorFallback));
×
762
  };
763

764
const ATTRIBUTE_LIST_CUTOFF = 100;
187✔
765
const attributeReducer = (attributes = []) =>
187!
766
  attributes.slice(0, ATTRIBUTE_LIST_CUTOFF).reduce(
19✔
767
    (accu, { name, scope }) => {
768
      if (!accu[scope]) {
380!
769
        accu[scope] = [];
×
770
      }
771
      accu[scope].push(name);
380✔
772
      return accu;
380✔
773
    },
774
    { identity: [], inventory: [], system: [], tags: [] }
775
  );
776

777
export const getDeviceAttributes = () => (dispatch, getState) =>
187✔
778
  GeneralApi.get(getAttrsEndpoint(getState().app.features.hasReporting)).then(({ data }) => {
21✔
779
    // TODO: remove the array fallback once the inventory attributes endpoint is fixed
780
    const { identity: identityAttributes, inventory: inventoryAttributes, system: systemAttributes, tags: tagAttributes } = attributeReducer(data || []);
18!
781
    return dispatch({
18✔
782
      type: DeviceConstants.SET_FILTER_ATTRIBUTES,
783
      attributes: { identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }
784
    });
785
  });
786

787
export const getReportingLimits = () => dispatch =>
187✔
788
  GeneralApi.get(`${reportingApiUrl}/devices/attributes`)
2✔
789
    .catch(err => commonErrorHandler(err, `filterable attributes limit & usage could not be retrieved.`, dispatch, commonErrorFallback))
×
790
    .then(({ data }) => {
791
      const { attributes, count, limit } = data;
1✔
792
      const groupedAttributes = attributeReducer(attributes);
1✔
793
      return Promise.resolve(dispatch({ type: DeviceConstants.SET_FILTERABLES_CONFIG, count, limit, attributes: groupedAttributes }));
1✔
794
    });
795

796
export const ensureVersionString = (software, fallback) =>
187✔
797
  software.length && software !== 'artifact_name' ? (software.endsWith('.version') ? software : `${software}.version`) : fallback;
1!
798

799
const getSingleReportData = (reportConfig, groups) => {
187✔
800
  const { attribute, group, software = '' } = reportConfig;
1!
801
  const filters = [{ key: 'status', scope: 'identity', operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: 'accepted' }];
1✔
802
  if (group) {
1!
803
    const staticGroupFilter = { key: 'group', scope: 'system', operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: group };
×
804
    const { cleanedFilters: groupFilters } = getGroupFilters(group, groups);
×
805
    filters.push(...(groupFilters.length ? groupFilters : [staticGroupFilter]));
×
806
  }
807
  const aggregationAttribute = ensureVersionString(software, attribute);
1✔
808
  return GeneralApi.post(`${reportingApiUrl}/devices/aggregate`, {
1✔
809
    aggregations: [{ attribute: aggregationAttribute, name: '*', scope: 'inventory', size: chartColorPalette.length }],
810
    filters: mapFiltersToTerms(filters)
811
  }).then(({ data }) => ({ data, reportConfig }));
1✔
812
};
813

814
export const defaultReportType = 'distribution';
187✔
815
export const defaultReports = [{ ...emptyChartSelection, group: null, attribute: 'artifact_name', type: defaultReportType }];
187✔
816

817
export const getReportsData = () => (dispatch, getState) => {
187✔
818
  const state = getState();
1✔
819
  const reports =
820
    getUserSettings(state).reports ||
1✔
821
    state.users.globalSettings[`${state.users.currentUser}-reports`] ||
822
    (Object.keys(state.devices.byId).length ? defaultReports : []);
1!
823
  return Promise.all(reports.map(report => getSingleReportData(report, getState().devices.groups))).then(results => {
1✔
824
    const devicesState = getState().devices;
1✔
825
    const totalDeviceCount = devicesState.byStatus.accepted.total;
1✔
826
    const newReports = results.map(({ data, reportConfig }) => {
1✔
827
      let { items, other_count } = data[0];
1✔
828
      const { attribute, group, software = '' } = reportConfig;
1!
829
      const dataCount = items.reduce((accu, item) => accu + item.count, 0);
2✔
830
      // the following is needed to show reports including both old (artifact_name) & current style (rootfs-image.version) device software
831
      const otherCount = !group && (software === rootfsImageVersion || attribute === 'artifact_name') ? totalDeviceCount - dataCount : other_count;
1!
832
      return { items, otherCount, total: otherCount + dataCount };
1✔
833
    });
834
    return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_REPORTS, reports: newReports }));
1✔
835
  });
836
};
837

838
const initializeDistributionData = (report, groups, devices, totalDeviceCount) => {
187✔
839
  const { attribute, group = '', software = '' } = report;
12!
840
  const effectiveAttribute = software ? software : attribute;
12!
841
  const { deviceIds, total = 0 } = groups[group] || {};
12✔
842
  const relevantDevices = groups[group] ? deviceIds.map(id => devices[id]) : Object.values(devices);
12!
843
  const distributionByAttribute = relevantDevices.reduce((accu, item) => {
12✔
844
    if (!item.attributes || item.status !== DEVICE_STATES.accepted) return accu;
26✔
845
    if (!accu[item.attributes[effectiveAttribute]]) {
19!
846
      accu[item.attributes[effectiveAttribute]] = 0;
19✔
847
    }
848
    accu[item.attributes[effectiveAttribute]] = accu[item.attributes[effectiveAttribute]] + 1;
19✔
849
    return accu;
19✔
850
  }, {});
851
  const distributionByAttributeSorted = Object.entries(distributionByAttribute).sort((pairA, pairB) => pairB[1] - pairA[1]);
12✔
852
  const items = distributionByAttributeSorted.map(([key, count]) => ({ key, count }));
19✔
853
  const dataCount = items.reduce((accu, item) => accu + item.count, 0);
19✔
854
  // the following is needed to show reports including both old (artifact_name) & current style (rootfs-image.version) device software
855
  const otherCount = (groups[group] ? total : totalDeviceCount) - dataCount;
12!
856
  return { items, otherCount, total: otherCount + dataCount };
12✔
857
};
858

859
export const deriveReportsData = () => (dispatch, getState) =>
187✔
860
  Promise.all([dispatch(getGroups()), dispatch(getDynamicGroups())]).then(() => {
12✔
861
    const { dynamic: dynamicGroups, static: staticGroups } = getGroupsSelector(getState());
12✔
862
    return Promise.all([
12✔
863
      ...staticGroups.map(group => dispatch(getAllGroupDevices(group))),
12✔
864
      ...dynamicGroups.map(group => dispatch(getAllDynamicGroupDevices(group)))
12✔
865
    ]).then(() => {
866
      const state = getState();
12✔
867
      const {
868
        groups: { byId: groupsById },
869
        byId,
870
        byStatus: {
871
          accepted: { total }
872
        }
873
      } = state.devices;
12✔
874
      const reports =
875
        getUserSettings(state).reports || state.users.globalSettings[`${state.users.currentUser}-reports`] || (Object.keys(byId).length ? defaultReports : []);
12!
876
      const newReports = reports.map(report => initializeDistributionData(report, groupsById, byId, total));
12✔
877
      return Promise.resolve(dispatch({ type: DeviceConstants.SET_DEVICE_REPORTS, reports: newReports }));
12✔
878
    });
879
  });
880

881
export const getDeviceConnect = id => dispatch =>
187✔
882
  GeneralApi.get(`${deviceConnect}/devices/${id}`).then(({ data }) => {
2✔
883
    let tasks = [
1✔
884
      dispatch({
885
        type: DeviceConstants.RECEIVE_DEVICE_CONNECT,
886
        device: { connect_status: data.status, connect_updated_ts: data.updated_ts, id }
887
      })
888
    ];
889
    tasks.push(Promise.resolve(data));
1✔
890
    return Promise.all(tasks);
1✔
891
  });
892

893
export const getSessionDetails = (sessionId, deviceId, userId, startDate, endDate) => () => {
187✔
894
  const createdAfter = startDate ? `&created_after=${Math.round(Date.parse(startDate) / 1000)}` : '';
4✔
895
  const createdBefore = endDate ? `&created_before=${Math.round(Date.parse(endDate) / 1000)}` : '';
4✔
896
  const objectSearch = `&object_id=${deviceId}`;
4✔
897
  return GeneralApi.get(`${auditLogsApiUrl}/logs?per_page=500${createdAfter}${createdBefore}&actor_id=${userId}${objectSearch}`).then(
4✔
898
    ({ data: auditLogEntries }) => {
899
      const { start, end } = auditLogEntries.reduce(
3✔
900
        (accu, item) => {
901
          if (item.meta?.session_id?.includes(sessionId)) {
3!
902
            accu.start = new Date(item.action.startsWith('open') ? item.time : accu.start);
3!
903
            accu.end = new Date(item.action.startsWith('close') ? item.time : accu.end);
3!
904
          }
905
          return accu;
3✔
906
        },
907
        { start: startDate || endDate, end: endDate || startDate }
9✔
908
      );
909
      return Promise.resolve({ start, end });
3✔
910
    }
911
  );
912
};
913

914
export const getDeviceFileDownloadLink = (deviceId, path) => () =>
187✔
915
  Promise.resolve(`${deviceConnect}/devices/${deviceId}/download?path=${encodeURIComponent(path)}`);
1✔
916

917
export const deviceFileUpload = (deviceId, path, file) => (dispatch, getState) => {
187✔
918
  var formData = new FormData();
1✔
919
  formData.append('path', path);
1✔
920
  formData.append('file', file);
1✔
921
  const uploadId = uuid();
1✔
922
  const cancelSource = new AbortController();
1✔
923
  const uploads = { ...getState().app.uploads, [uploadId]: { inprogress: true, uploadProgress: 0, cancelSource } };
1✔
924
  return Promise.all([
1✔
925
    dispatch(setSnackbar('Uploading file')),
926
    dispatch({ type: UPLOAD_PROGRESS, uploads }),
927
    GeneralApi.uploadPut(`${deviceConnect}/devices/${deviceId}/upload`, formData, e => dispatch(progress(e, uploadId)), cancelSource.signal)
×
928
  ])
929
    .then(() => Promise.resolve(dispatch(setSnackbar('Upload successful', TIMEOUTS.fiveSeconds))))
1✔
930
    .catch(err => {
931
      if (isCancel(err)) {
×
932
        return dispatch(setSnackbar('The upload has been cancelled', TIMEOUTS.fiveSeconds));
×
933
      }
934
      return commonErrorHandler(err, `Error uploading file to device.`, dispatch);
×
935
    })
936
    .finally(() => dispatch(cleanUpUpload(uploadId)));
1✔
937
};
938

939
export const getDeviceAuth = id => dispatch =>
187✔
940
  Promise.resolve(dispatch(getDevicesWithAuth([{ id }]))).then(results => {
6✔
941
    if (results[results.length - 1]) {
5!
942
      return Promise.resolve(results[results.length - 1][0]);
5✔
943
    }
944
    return Promise.resolve();
×
945
  });
946

947
export const getDevicesWithAuth = devices => (dispatch, getState) =>
187✔
948
  devices.length
63✔
949
    ? GeneralApi.get(`${deviceAuthV2}/devices?id=${devices.map(device => device.id).join('&id=')}`)
63✔
950
        .then(({ data: receivedDevices }) => {
951
          const { devicesById } = reduceReceivedDevices(receivedDevices, [], getState());
59✔
952
          return Promise.all([dispatch({ type: DeviceConstants.RECEIVE_DEVICES, devicesById }), Promise.resolve(receivedDevices)]);
59✔
953
        })
954
        .catch(err => commonErrorHandler(err, `Error: ${err}`, dispatch))
×
955
    : Promise.resolve([[], []]);
956

957
const maybeUpdateDevicesByStatus = (deviceId, authId) => (dispatch, getState) => {
187✔
958
  const devicesState = getState().devices;
4✔
959
  const device = devicesState.byId[deviceId];
4✔
960
  const hasMultipleAuthSets = authId ? device.auth_sets.filter(authset => authset.id !== authId).length > 0 : false;
4✔
961
  if (!hasMultipleAuthSets && Object.values(DEVICE_STATES).includes(device.status)) {
4!
962
    const deviceIds = devicesState.byStatus[device.status].deviceIds.filter(id => id !== deviceId);
8✔
963
    return Promise.resolve(
4✔
964
      dispatch({
965
        type: DeviceConstants[`SET_${device.status.toUpperCase()}_DEVICES`],
966
        deviceIds,
967
        forceUpdate: true,
968
        status: device.status,
969
        total: Math.max(0, devicesState.byStatus[device.status].total - 1)
970
      })
971
    );
972
  }
973
  return Promise.resolve();
×
974
};
975

976
export const updateDeviceAuth = (deviceId, authId, status) => (dispatch, getState) =>
187✔
977
  GeneralApi.put(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}/status`, { status })
2✔
978
    .then(() => Promise.all([dispatch(getDeviceAuth(deviceId)), dispatch(setSnackbar('Device authorization status was updated successfully'))]))
2✔
979
    .catch(err => commonErrorHandler(err, 'There was a problem updating the device authorization status:', dispatch))
×
980
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))))
2✔
981
    .finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })));
2✔
982

983
export const updateDevicesAuth = (deviceIds, status) => (dispatch, getState) => {
187✔
984
  let devices = getState().devices.byId;
1✔
985
  const deviceIdsWithoutAuth = deviceIds.reduce((accu, id) => (devices[id].auth_sets ? accu : [...accu, { id }]), []);
2!
986
  return dispatch(getDevicesWithAuth(deviceIdsWithoutAuth)).then(() => {
1✔
987
    devices = getState().devices.byId;
1✔
988
    // for each device, get id and id of authset & make api call to accept
989
    // if >1 authset, skip instead
990
    const deviceAuthUpdates = deviceIds.map(id => {
1✔
991
      const device = devices[id];
2✔
992
      if (device.auth_sets.length !== 1) {
2✔
993
        return Promise.reject();
1✔
994
      }
995
      // api call device.id and device.authsets[0].id
996
      return dispatch(updateDeviceAuth(device.id, device.auth_sets[0].id, status)).catch(err =>
1✔
997
        commonErrorHandler(err, 'The action was stopped as there was a problem updating a device authorization status: ', dispatch)
×
998
      );
999
    });
1000
    return Promise.allSettled(deviceAuthUpdates).then(results => {
1✔
1001
      const { skipped, count } = results.reduce(
1✔
1002
        (accu, item) => {
1003
          if (item.status === 'rejected') {
2✔
1004
            accu.skipped = accu.skipped + 1;
1✔
1005
          } else {
1006
            accu.count = accu.count + 1;
1✔
1007
          }
1008
          return accu;
2✔
1009
        },
1010
        { skipped: 0, count: 0 }
1011
      );
1012
      const message = getSnackbarMessage(skipped, count);
1✔
1013
      // break if an error occurs, display status up til this point before error message
1014
      return dispatch(setSnackbar(message));
1✔
1015
    });
1016
  });
1017
};
1018

1019
export const deleteAuthset = (deviceId, authId) => (dispatch, getState) =>
187✔
1020
  GeneralApi.delete(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}`)
1✔
1021
    .then(() => Promise.all([dispatch(setSnackbar('Device authorization status was updated successfully'))]))
1✔
1022
    .catch(err => commonErrorHandler(err, 'There was a problem updating the device authorization status:', dispatch))
×
1023
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))))
1✔
1024
    .finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })));
1✔
1025

1026
export const preauthDevice = authset => dispatch =>
187✔
1027
  GeneralApi.post(`${deviceAuthV2}/devices`, authset)
2✔
1028
    .catch(err => {
1029
      if (err.response.status === 409) {
1!
1030
        return Promise.reject('A device with a matching identity data set already exists');
1✔
1031
      }
1032
      commonErrorHandler(err, 'The device could not be added:', dispatch);
×
1033
      return Promise.reject();
×
1034
    })
1035
    .then(() => Promise.resolve(dispatch(setSnackbar('Device was successfully added to the preauthorization list', TIMEOUTS.fiveSeconds))));
1✔
1036

1037
export const decommissionDevice = (deviceId, authId) => (dispatch, getState) =>
187✔
1038
  GeneralApi.delete(`${deviceAuthV2}/devices/${deviceId}`)
1✔
1039
    .then(() => Promise.resolve(dispatch(setSnackbar('Device was decommissioned successfully'))))
1✔
1040
    .catch(err => commonErrorHandler(err, 'There was a problem decommissioning the device:', dispatch))
×
1041
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))))
1✔
1042
    // trigger reset of device list list!
1043
    .finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })));
1✔
1044

1045
export const getDeviceConfig = deviceId => dispatch =>
187✔
1046
  GeneralApi.get(`${deviceConfig}/${deviceId}`)
4✔
1047
    .then(({ data }) => {
1048
      let tasks = [
2✔
1049
        dispatch({
1050
          type: DeviceConstants.RECEIVE_DEVICE_CONFIG,
1051
          device: { id: deviceId, config: data }
1052
        })
1053
      ];
1054
      tasks.push(Promise.resolve(data));
2✔
1055
      return Promise.all(tasks);
2✔
1056
    })
1057
    .catch(err => {
1058
      // if we get a proper error response we most likely queried a device without an existing config check-in and we can just ignore the call
1059
      if (err.response?.data?.error.status_code !== 404) {
1!
1060
        return commonErrorHandler(err, `There was an error retrieving the configuration for device ${deviceId}.`, dispatch, commonErrorFallback);
×
1061
      }
1062
    });
1063

1064
export const setDeviceConfig = (deviceId, config) => dispatch =>
187✔
1065
  GeneralApi.put(`${deviceConfig}/${deviceId}`, config)
1✔
1066
    .catch(err => commonErrorHandler(err, `There was an error setting the configuration for device ${deviceId}.`, dispatch, commonErrorFallback))
×
1067
    .then(() => Promise.resolve(dispatch(getDeviceConfig(deviceId))));
1✔
1068

1069
export const applyDeviceConfig = (deviceId, configDeploymentConfiguration, isDefault, config) => (dispatch, getState) =>
187✔
1070
  GeneralApi.post(`${deviceConfig}/${deviceId}/deploy`, configDeploymentConfiguration)
1✔
1071
    .catch(err => commonErrorHandler(err, `There was an error deploying the configuration to device ${deviceId}.`, dispatch, commonErrorFallback))
×
1072
    .then(({ data }) => {
1073
      let tasks = [dispatch(getSingleDeployment(data.deployment_id))];
1✔
1074
      if (isDefault) {
1!
1075
        const { previous } = getState().users.globalSettings.defaultDeviceConfig;
×
1076
        tasks.push(dispatch(saveGlobalSettings({ defaultDeviceConfig: { current: config, previous } })));
×
1077
      }
1078
      return Promise.all(tasks);
1✔
1079
    });
1080

1081
export const setDeviceTags = (deviceId, tags) => dispatch =>
187✔
1082
  // to prevent tag set failures, retrieve the device & use the freshest etag we can get
1083
  Promise.resolve(dispatch(getDeviceById(deviceId))).then(device => {
3✔
1084
    const headers = device.etag ? { 'If-Match': device.etag } : {};
3!
1085
    return GeneralApi.put(
3✔
1086
      `${inventoryApiUrl}/devices/${deviceId}/tags`,
1087
      Object.entries(tags).map(([name, value]) => ({ name, value })),
3✔
1088
      { headers }
1089
    )
1090
      .catch(err => commonErrorHandler(err, `There was an error setting tags for device ${deviceId}.`, dispatch, 'Please check your connection.'))
×
1091
      .then(() => Promise.all([dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device: { ...device, tags } }), dispatch(setSnackbar('Device name changed'))]));
2✔
1092
  });
1093

1094
export const getDeviceTwin = (deviceId, integration) => (dispatch, getState) => {
187✔
1095
  let providerResult = {};
3✔
1096
  return GeneralApi.get(`${iotManagerBaseURL}/devices/${deviceId}/state`)
3✔
1097
    .then(({ data }) => {
1098
      providerResult = { ...data, twinError: '' };
2✔
1099
    })
1100
    .catch(err => {
1101
      providerResult = {
×
1102
        twinError: `There was an error getting the ${DeviceConstants.EXTERNAL_PROVIDER[
1103
          integration.provider
1104
        ].twinTitle.toLowerCase()} for device ${deviceId}. ${err}`
1105
      };
1106
    })
1107
    .finally(() =>
1108
      Promise.resolve(
2✔
1109
        dispatch({
1110
          type: DeviceConstants.RECEIVE_DEVICE,
1111
          device: {
1112
            ...getState().devices.byId[deviceId],
1113
            twinsByIntegration: {
1114
              ...getState().devices.byId[deviceId].twinsByIntegration,
1115
              ...providerResult
1116
            }
1117
          }
1118
        })
1119
      )
1120
    );
1121
};
1122

1123
export const setDeviceTwin = (deviceId, integration, settings) => (dispatch, getState) =>
187✔
1124
  GeneralApi.put(`${iotManagerBaseURL}/devices/${deviceId}/state/${integration.id}`, { desired: settings })
1✔
1125
    .catch(err =>
1126
      commonErrorHandler(
×
1127
        err,
1128
        `There was an error updating the ${DeviceConstants.EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}.`,
1129
        dispatch
1130
      )
1131
    )
1132
    .then(() => {
1133
      const { twinsByIntegration = {} } = getState().devices.byId[deviceId];
1✔
1134
      const { [integration.id]: currentState = {} } = twinsByIntegration;
1✔
1135
      return Promise.resolve(
1✔
1136
        dispatch({
1137
          type: DeviceConstants.RECEIVE_DEVICE,
1138
          device: {
1139
            ...getState().devices.byId[deviceId],
1140
            twinsByIntegration: {
1141
              ...twinsByIntegration,
1142
              [integration.id]: {
1143
                ...currentState,
1144
                desired: settings
1145
              }
1146
            }
1147
          }
1148
        })
1149
      );
1150
    });
1151

1152
const prepareSearchArguments = ({ filters, group, state, status }) => {
187✔
1153
  const { filterTerms } = convertDeviceListStateToFilters({ filters, group, offlineThreshold: state.app.offlineThreshold, selectedIssues: [], status });
4✔
1154
  const { columnSelection = [] } = getUserSettings(state);
4!
1155
  const selectedAttributes = columnSelection.map(column => ({ attribute: column.key, scope: column.scope }));
4✔
1156
  const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(state).attribute }, ...selectedAttributes];
4✔
1157
  return { attributes, filterTerms };
4✔
1158
};
1159

1160
export const getSystemDevices =
1161
  (id, options = {}) =>
187✔
1162
  (dispatch, getState) => {
1✔
1163
    const { page = defaultPage, perPage = defaultPerPage, sortOptions = [] } = options;
1✔
1164
    const state = getState();
1✔
1165
    let device = getDeviceByIdSelector(state, id);
1✔
1166
    const { attributes: deviceAttributes = {} } = device;
1!
1167
    const { mender_gateway_system_id = '' } = deviceAttributes;
1✔
1168
    const { hasFullFiltering } = getTenantCapabilities(state);
1✔
1169
    if (!hasFullFiltering) {
1!
1170
      return Promise.resolve();
×
1171
    }
1172
    const filters = [
1✔
1173
      { ...emptyFilter, key: 'mender_is_gateway', operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: 'true', scope: 'inventory' },
1174
      { ...emptyFilter, key: 'mender_gateway_system_id', value: mender_gateway_system_id, scope: 'inventory' }
1175
    ];
1176
    const { attributes, filterTerms } = prepareSearchArguments({ filters, state });
1✔
1177

1178
    return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
1✔
1179
      page,
1180
      per_page: perPage,
1181
      filters: filterTerms,
1182
      sort: sortOptions,
1183
      attributes
1184
    })
1185
      .catch(err => commonErrorHandler(err, `There was an error getting system devices device ${id}.`, dispatch, 'Please check your connection.'))
×
1186
      .then(({ data, headers }) => {
1187
        const state = getState();
1✔
1188
        const { devicesById, ids } = reduceReceivedDevices(data, [], state);
1✔
1189
        const device = {
1✔
1190
          ...state.devices.byId[id],
1191
          systemDeviceIds: ids,
1192
          systemDeviceTotal: Number(headers[headerNames.total])
1193
        };
1194
        return Promise.resolve(
1✔
1195
          dispatch({
1196
            type: DeviceConstants.RECEIVE_DEVICES,
1197
            devicesById: {
1198
              ...devicesById,
1199
              [id]: device
1200
            }
1201
          })
1202
        );
1203
      });
1204
  };
1205

1206
export const getGatewayDevices = deviceId => (dispatch, getState) => {
187✔
1207
  const state = getState();
1✔
1208
  let device = getDeviceByIdSelector(state, deviceId);
1✔
1209
  const { attributes = {} } = device;
1!
1210
  const { mender_gateway_system_id = '' } = attributes;
1!
1211
  const filters = [
1✔
1212
    { ...emptyFilter, key: 'id', operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: deviceId, scope: 'identity' },
1213
    { ...emptyFilter, key: 'mender_is_gateway', value: 'true', scope: 'inventory' },
1214
    { ...emptyFilter, key: 'mender_gateway_system_id', value: mender_gateway_system_id, scope: 'inventory' }
1215
  ];
1216
  const { attributes: attributeSelection, filterTerms } = prepareSearchArguments({ filters, state });
1✔
1217
  return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
1✔
1218
    page: 1,
1219
    per_page: MAX_PAGE_SIZE,
1220
    filters: filterTerms,
1221
    attributes: attributeSelection
1222
  }).then(({ data }) => {
1223
    const { ids } = reduceReceivedDevices(data, [], getState());
1✔
1224
    let tasks = ids.map(deviceId => dispatch(getDeviceInfo(deviceId)));
1✔
1225
    tasks.push(dispatch({ type: DeviceConstants.RECEIVE_DEVICE, device: { ...getState().devices.byId[deviceId], gatewayIds: ids } }));
1✔
1226
    return Promise.all(tasks);
1✔
1227
  });
1228
};
1229

1230
export const geoAttributes = ['geo-lat', 'geo-lon'].map(attribute => ({ attribute, scope: 'inventory' }));
374✔
1231
export const getDevicesInBounds = (bounds, group) => (dispatch, getState) => {
187✔
1232
  const state = getState();
×
1233
  const { filterTerms } = convertDeviceListStateToFilters({
×
1234
    group: group === DeviceConstants.ALL_DEVICES ? undefined : group,
×
1235
    groups: state.devices.groups,
1236
    status: DEVICE_STATES.accepted
1237
  });
1238
  return GeneralApi.post(getSearchEndpoint(state.app.features.hasReporting), {
×
1239
    page: 1,
1240
    per_page: MAX_PAGE_SIZE,
1241
    filters: filterTerms,
1242
    attributes: geoAttributes,
1243
    geo_bounding_box_filter: {
1244
      geo_bounding_box: {
1245
        location: {
1246
          top_left: { lat: bounds._northEast.lat, lon: bounds._southWest.lng },
1247
          bottom_right: { lat: bounds._southWest.lat, lon: bounds._northEast.lng }
1248
        }
1249
      }
1250
    }
1251
  }).then(({ data }) => {
1252
    const { devicesById } = reduceReceivedDevices(data, [], getState());
×
1253
    return Promise.resolve(dispatch({ type: DeviceConstants.RECEIVE_DEVICES, devicesById }));
×
1254
  });
1255
};
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