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

mendersoftware / gui / 908425489

pending completion
908425489

Pull #3799

gitlab-ci

mzedel
chore: aligned loader usage in devices list with deployment devices list

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3799: MEN-6553

4406 of 6423 branches covered (68.6%)

18 of 19 new or added lines in 3 files covered. (94.74%)

1777 existing lines in 167 files now uncovered.

8329 of 10123 relevant lines covered (82.28%)

144.7 hits per line

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

84.47
/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, 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
  getDeviceFilters,
22
  getDeviceTwinIntegrations,
23
  getGroups as getGroupsSelector,
24
  getIdAttribute,
25
  getTenantCapabilities,
26
  getUserCapabilities,
27
  getUserSettings
28
} from '../selectors';
29
import { chartColorPalette } from '../themes/Mender';
30
import { getDeviceMonitorConfig, getLatestDeviceAlerts } from './monitorActions';
31

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

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

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

57
export const getSearchEndpoint = hasReporting => (hasReporting ? `${reportingApiUrl}/devices/search` : `${inventoryApiUrlV2}/filters/search`);
190!
58

59
const getAttrsEndpoint = hasReporting => (hasReporting ? `${reportingApiUrl}/devices/search/attributes` : `${inventoryApiUrlV2}/filters/attributes`);
190✔
60

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

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

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

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

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

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

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

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

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

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

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

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

311
const reduceReceivedDevices = (devices, ids, state, status) =>
190✔
312
  devices.reduce(
119✔
313
    (accu, device) => {
314
      const stateDevice = state.devices.byId[device.id] || {};
120✔
315
      const {
316
        attributes: storedAttributes = {},
3✔
317
        identity_data: storedIdentity = {},
3✔
318
        monitor: storedMonitor = {},
96✔
319
        tags: storedTags = {},
96✔
320
        group: storedGroup
321
      } = stateDevice;
120✔
322
      const { identity, inventory, monitor, system = {}, tags } = mapDeviceAttributes(device.attributes);
120!
323
      // 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
324
      // for device_type and artifact_name, potentially overwriting existing info, so rely on stored information instead if there are no attributes
325
      device.attributes = device.attributes ? { ...storedAttributes, ...inventory } : storedAttributes;
120✔
326
      device.tags = { ...storedTags, ...tags };
120✔
327
      device.group = system.group ?? storedGroup;
120✔
328
      device.monitor = { ...storedMonitor, ...monitor };
120✔
329
      device.identity_data = { ...storedIdentity, ...identity, ...(device.identity_data ? device.identity_data : {}) };
120✔
330
      device.status = status ? status : device.status || identity.status;
120✔
331
      device.created_ts = getEarliestTs(getEarliestTs(system.created_ts, device.created_ts), stateDevice.created_ts);
120✔
332
      device.updated_ts = getLatestTs(getLatestTs(system.updated_ts, device.updated_ts), stateDevice.updated_ts);
120✔
333
      device.isNew = new Date(device.created_ts) > new Date(state.app.newThreshold);
120✔
334
      device.isOffline = new Date(device.updated_ts) < new Date(state.app.offlineThreshold);
120✔
335
      accu.devicesById[device.id] = { ...stateDevice, ...device };
120✔
336
      accu.ids.push(device.id);
120✔
337
      return accu;
120✔
338
    },
339
    { ids, devicesById: {} }
340
  );
341

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

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

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

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

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

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

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

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

558
export const getAllDeviceCounts = () => dispatch =>
190✔
559
  Promise.all([DEVICE_STATES.accepted, DEVICE_STATES.pending].map(status => dispatch(getDeviceCount(status))));
2✔
560

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

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

611
const convertIssueOptionsToFilters = (issuesSelection, filtersState = {}) =>
190!
612
  issuesSelection.map(item => {
69✔
613
    if (typeof DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule.value === 'function') {
5✔
614
      return { ...DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule, value: DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule.value(filtersState) };
2✔
615
    }
616
    return DeviceConstants.DEVICE_ISSUE_OPTIONS[item].filterRule;
3✔
617
  });
618

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

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

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

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

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

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

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

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

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

812
export const defaultReportType = 'distribution';
190✔
813
export const defaultReports = [{ ...emptyChartSelection, group: null, attribute: 'artifact_name', type: defaultReportType }];
190✔
814

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

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

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

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

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

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

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

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

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

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

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

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

1016
export const deleteAuthset = (deviceId, authId) => dispatch =>
190✔
1017
  GeneralApi.delete(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}`)
1✔
1018
    .then(() => Promise.all([dispatch(setSnackbar('Device authorization status was updated successfully'))]))
1✔
UNCOV
1019
    .catch(err => commonErrorHandler(err, 'There was a problem updating the device authorization status:', dispatch))
×
1020
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))));
1✔
1021

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

1033
export const decommissionDevice = (deviceId, authId) => dispatch =>
190✔
1034
  GeneralApi.delete(`${deviceAuthV2}/devices/${deviceId}`)
1✔
1035
    .then(() => Promise.resolve(dispatch(setSnackbar('Device was decommissioned successfully'))))
1✔
UNCOV
1036
    .catch(err => commonErrorHandler(err, 'There was a problem decommissioning the device:', dispatch))
×
1037
    .then(() => Promise.resolve(dispatch(maybeUpdateDevicesByStatus(deviceId, authId))));
1✔
1038

1039
export const getDeviceConfig = deviceId => dispatch =>
190✔
1040
  GeneralApi.get(`${deviceConfig}/${deviceId}`)
4✔
1041
    .then(({ data }) => {
1042
      let tasks = [
2✔
1043
        dispatch({
1044
          type: DeviceConstants.RECEIVE_DEVICE_CONFIG,
1045
          device: { id: deviceId, config: data }
1046
        })
1047
      ];
1048
      tasks.push(Promise.resolve(data));
2✔
1049
      return Promise.all(tasks);
2✔
1050
    })
1051
    .catch(err => {
1052
      // 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
1053
      if (err.response?.data?.error.status_code !== 404) {
1!
UNCOV
1054
        return commonErrorHandler(err, `There was an error retrieving the configuration for device ${deviceId}.`, dispatch, commonErrorFallback);
×
1055
      }
1056
    });
1057

1058
export const setDeviceConfig = (deviceId, config) => dispatch =>
190✔
1059
  GeneralApi.put(`${deviceConfig}/${deviceId}`, config)
1✔
UNCOV
1060
    .catch(err => commonErrorHandler(err, `There was an error setting the configuration for device ${deviceId}.`, dispatch, commonErrorFallback))
×
1061
    .then(() => Promise.resolve(dispatch(getDeviceConfig(deviceId))));
1✔
1062

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

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

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

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

1146
const prepareSearchArguments = ({ filters, group, state, status }) => {
190✔
1147
  const { filterTerms } = convertDeviceListStateToFilters({ filters, group, offlineThreshold: state.app.offlineThreshold, selectedIssues: [], status });
4✔
1148
  const { columnSelection = [] } = getUserSettings(state);
4!
1149
  const selectedAttributes = columnSelection.map(column => ({ attribute: column.key, scope: column.scope }));
4✔
1150
  const attributes = [...defaultAttributes, { scope: 'identity', attribute: getIdAttribute(state).attribute }, ...selectedAttributes];
4✔
1151
  return { attributes, filterTerms };
4✔
1152
};
1153

1154
export const getSystemDevices =
1155
  (id, options = {}) =>
190✔
1156
  (dispatch, getState) => {
1✔
1157
    const { page = defaultPage, perPage = defaultPerPage, sortOptions = [] } = options;
1✔
1158
    const state = getState();
1✔
1159
    let device = state.devices.byId[id];
1✔
1160
    const { attributes: deviceAttributes = {} } = device;
1!
1161
    const { mender_gateway_system_id = '' } = deviceAttributes;
1✔
1162
    const { hasFullFiltering } = getTenantCapabilities(state);
1✔
1163
    if (!hasFullFiltering) {
1!
UNCOV
1164
      return Promise.resolve();
×
1165
    }
1166
    const filters = [
1✔
1167
      { ...emptyFilter, key: 'mender_is_gateway', operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: 'true', scope: 'inventory' },
1168
      { ...emptyFilter, key: 'mender_gateway_system_id', value: mender_gateway_system_id, scope: 'inventory' }
1169
    ];
1170
    const { attributes, filterTerms } = prepareSearchArguments({ filters, state });
1✔
1171

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

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

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